假设我有一堂课:
class pdoc {
private static $db_connect_pool;
public static function openConnect() {
try {
$connect_options_arr = array(PDO::ATTR_PERSISTENT => true);
self::$db_connect_pool[''.DB_DRIVER.'_'.DB_NAME.''] = new PDO("".DB_DRIVER.":host=".DB_HOST.";db_name=".DB_NAME."", DB_USER, DB_PASS, $connect_options_arr);
} catch (Exception $e) {
print_r($e);
}
}
public static function getConnection() {
return self::$db_connect_pool[''.DB_DRIVER.'_'.DB_NAME.''];
}
public static function qry($sql) {
self::openConnect();
$db_handle = self::getConnection();
$st_handle = $db_handle->prepare($sql);
return $st_handle->execute();
}
}
然后,调用类:
$sql = "SELECT * FROM sometable";
if(pdoc::qry($sql)) echo "y";
else echo "n";
为什么代码总是返回n
?我检查了已成功连接的连接,但是当我尝试执行一些查询时,它什么也没返回。有任何想法吗?谢谢。
更新(@Robbie 的代码)
class pdoc {
private static $db_connect_pool;
public static function openConnect() {
try {
$connect_options_arr = array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
self::$db_connect_pool[''.DB_DRIVER.'_'.DB_NAME.''] = new PDO("".DB_DRIVER.":host=".DB_HOST.";db_name=".DB_NAME."", DB_USER, DB_PASS, $connect_options_arr);
} catch (Exception $e) {
print_r($e);
}
}
public static function getConnection() {
return self::$db_connect_pool[''.DB_DRIVER.'_'.DB_NAME.''];
}
public static function qry($sql) {
self::openConnect();
$db_handle = self::getConnection();
try {
$st_handle = $db_handle->prepare($sql);
$retval = $st_handle->execute(); //--> Got error on this line
} catch (Exception $e) {
Die('Need to handle this error. $e has all the details');
}
return $retval;
}
}
错误说:exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected'
。
回答
改变:
... new PDO("".DB_DRIVER.":host=".DB_HOST.";db_name=".DB_NAME."", ...
进入:
... new PDO("".DB_DRIVER.":host=".DB_HOST.";dbname=".DB_NAME."", ...
在捕获错误消息(来自更新的代码)并参考此线程后,我发现该dbname
部分已按照dn_name
我的代码编写。所以我把它改成dbname
它,它工作得很好!感谢@Robbie 提供您的代码!:)