PHP PDO潜在的逻辑错误

我是
PHP新手,想知道为什么这段代码没有向DB插入任何内容(返回0).我确定它必须是一个逻辑错误,因为我没有收到任何错误消息.

class DbConnection {
    protected $db_conn;
    public $db_host = "localhost";
    public $db_name = "todo";
    public $db_user = "root";
    public $db_pass = "";

    function connect () {
        try {
            $this->db_conn = new PDO ("mysql: host = $this->db_host; dbname = $this->db_name", $this->db_user, $this->db_pass);
            return $this->db_conn;
        }
        catch (PDOException $e) {
            return $e->getMessage ();
        }
    }
}

class ManageUsers {
    public $link;

    function __construct () {
        $db_connecton = new DbConnection ();
        $this->link = $db_connecton->connect ();
        return $this->link;
    }

    function registerUsers ($username, $password, $ip_address, $reg_time, $reg_date) {
        $query = $this->link->prepare("INSERT INTO users (username, password, ip_address, reg_time, reg_date) VALUES (?,?,?,?,?)");
        $values = array ($username, $password, $ip_address, $reg_time, $reg_date);
        $query->execute ($values);
        $counts = $query->rowCount ();
        return $counts;
    }

}

$users = new ManageUsers ();
echo $users->registerUsers ("bob", "lassie", "127.0.0.2", "13:37", "03-14-15");

最佳答案 你不应该在你的PDO连接中放置空格,否则它会假设奇怪的事情,例如它认为你的db名称是:[space] todo等等,所以只需删除连接字符串中的每个空格,如下所示:

$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
                             //^     ^              ^      ^no spaces
点赞