PHP PDO潜在的逻辑错误 [英] PHP PDO potential logical error

查看:54
本文介绍了PHP PDO潜在的逻辑错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to PHP and would like to know why this code doesn't insert anything to the DB (returns 0). I'm sure it has to be a logical error, as I'm not getting any error messages.

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连接中放置空格,否则它将承担一些奇怪的事情,例如它认为您的数据库名称是:[space]todo,依此类推,因此只需删除连接字符串中的每个空格,如下所示:

You shouldn't put spaces in your PDO connection otherwise it will assume strange things e.g. it thinks that you db name is: [space]todo and so on, so just remove every space in your connection string, like this:

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

这篇关于PHP PDO潜在的逻辑错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆