[英]PHP PDO query not executed
我正在嘗試通過綁定參數來執行查詢。 我在DB.php中有一個query()函數,該函數將查詢和參數作為參數。 在此函數中,使用prepare()成功准備了查詢,但是當我在其上使用execute()時,查詢不執行。(我沒有在屏幕上打印“成功”。)
我該怎么辦? 這樣查詢才能成功執行。
碼:
db.php中
<?php
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct() {
try {
$this->_pdo = new PDO('mysql:host = '. Config::get('mysql/host').'; dbname ='. Config::get('mysql/db').'', Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()) {
echo "Success";
}
}
}
}
的index.php
<?php
require_once 'core/init.php';
DB::getInstance()->query("SELECT username FROM users WHERE username = ?", array('alex'));
這種本來就很聰明的類有很多缺陷,例如缺少錯誤報告和有狀態性。 要使其理智,請按如下所示進行更改:
class DB {
private static $_instance = null;
protected function __construct() {
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->_pdo = new PDO('mysql:host = '. Config::get('mysql/host').'; dbname ='. Config::get('mysql/db').'', Config::get('mysql/username'), Config::get('mysql/password'), $opt);
}
public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$stmt = $this->_pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
}
}
請注意,您通常必須能夠看到PHP錯誤。 明顯。
但是,此類無法訪問某些PDO功能。 您可以手動添加它們,但是我個人更喜歡使用一些魔術使它們全部自動被調用。 因此,我編寫了自己的PDO包裝器 ,如果我必須使用PDO而不是自己的數據庫包裝器 ,這對我很有幫助。 這是漏水的抽象太多,因為它使用PDO語句返回數據,但一個必須絕對瘋狂拋售是輝煌的機制,可以在十幾種不同的格式返回數據。
無論如何絕對不應該有像
$_query,
$_error,
$_results,
因為它們會在您的班級中引入狀態,而狀態必須嚴格是無狀態的。
另一個帶有以下內容的語句:
print_r($this->_query->errorInfo());
顯示:數組([0] => 3D000 [1] => 1046 [2] =>未選擇數據庫)
然后我檢查了PDO連接線:
更改此行:
$this->_pdo = new PDO('mysql:host = '. Config::get('mysql/host').';dbname =' .Config::get('mysql/db').'', Config::get('mysql/username'), Config::get('mysql/password'));
變成這個:
$this->_pdo = new PDO('mysql:host = '. Config::get('mysql/host').';dbname=' .Config::get('mysql/db').'', Config::get('mysql/username'), Config::get('mysql/password'));
刪除dbname之后的空格,它起作用了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.