PHP PDO潜在的逻辑错误
PHP PDO potential logical error
我是 PHP 的新手,想知道为什么这段代码没有向数据库中插入任何内容 (returns 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");
你不应该把 spaces 放在你的 PDO
连接中,否则它会假设奇怪的东西,例如它认为您的数据库名称是:[space]todo
等等,所以只需删除连接字符串中的每个 space,如下所示:
$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
//^ ^ ^ ^no spaces
我是 PHP 的新手,想知道为什么这段代码没有向数据库中插入任何内容 (returns 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");
你不应该把 spaces 放在你的 PDO
连接中,否则它会假设奇怪的东西,例如它认为您的数据库名称是:[space]todo
等等,所以只需删除连接字符串中的每个 space,如下所示:
$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
//^ ^ ^ ^no spaces