我的PHP课程有问题

时间:2016-01-09 04:00:39

标签: php mysql pdo

我有一个我从头开始构建的自定义PHP类,它用于连接,运行准备好的查询,输出和断开数据库。

问题是我不得不打多个错误。

这是其他修复后的最新版本。

  

警告:PDO :: __ construct():MySQL服务器在第23行的E:\ UniServerZ \ www \ simple db \ index.php中消失警告:PDO :: __ construct():读取问候数据包时出错。第23行的E:\ UniServerZ \ www \ simple db \ index.php中的PID = 8404警告:未捕获的异常' PDOException'消息' SQLSTATE [HY000] [2006] MySQL服务器已经消失了#39;在E:\ UniServerZ \ www \ simple db \ index.php:23堆栈跟踪:#0 E:\ UniServerZ \ www \ simple db \ index.php(23):PDO-> __ construct(' mysql: host = loca ...',' root','密码')#1 E:\ UniServerZ \ www \ simple db \ index.php(53):simpleDB- > connectToDB()#2 {main}在第23行的E:\ UniServerZ \ www \ simple db \ index.php中抛出致命错误:在E:\ UniServerZ \ www \ simple db \ index中超出了30秒的最大执行时间第23行的.php

我无法弄清楚,我的登录详情,主机详细信息等等都是正确的,所以我不确定现在该做什么,我确实在线阅读了一些文章,但是他们没有多大帮助,所以我在这里。

这是我的类和连接代码:

<?php
ini_set("display_errors", 1); 
error_reporting(E_ALL);

class fooBarBaz {
    protected $conn;
    private $host;
    private $username;
    private $password;
    private $db;
    private $driver;

    public function __construct($driver, $host, $db, $user, $pass) {
        $this->driver = $driver;
        $this->host = $host;
        $this->db = $db;
        $this->username = $user;
        $this->password = $pass;
    }

    public function connecterino() {
        try {
            $this->conn = new PDO($this->driver . ':host=' . $this->host .';dbname=' . $this->db . ';charset=utf8', $this->username, $this->password);
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    }

    public function queryForStuff($preparedQuery, $params) {
        try {
            $stmt = $this->conn->prepare($preparedQuery);
            $exec = $stmt->execute($params);
            return $stmt;
        } catch(PDOException $e) {
            echo 'Error: ' . $e->getMessage();
        }
    }

    public function getResultOfThatStuff($sql) {
        $data = $sql->fetchAll(PDO::FETCH_ASSOC);
        foreach($data as $row){
            print_r($row);
        }
    }

    public function disconnectDB() {
        $this->conn = null;
    }
}

try {
    $db = new fooBarBaz("mysql", "localhost:8000", "myDatabase", "root", "root");
    $db->connecterino();
    $query = $db->queryForStuff("select id from songs where id != :1", [":1" => "2"]);
    $db->getResultOfThatStuff($query);
} catch(PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}
?>

如何让这段代码按预期完全运行?

我做错了什么/我是否盲目?

感谢。

1 个答案:

答案 0 :(得分:3)

如果您要连接到默认端口以外的端口,DSN必须看起来像

mysql:host=localhost;port=8000;dbname=test;charset=utf8

而不是

<击> MySQL的:主机=本地主机:8000dbname =测试;字符集= UTF8