Assume that I have a class:
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();
}
}
Then, to call the class:
$sql = "SELECT * FROM sometable";
if(pdoc::qry($sql)) echo "y";
else echo "n";
Why the code always return n? I have check the connection that has been connected successfully, but while I’ve tried to execute some query, it returns nothing. Any ideas? Thanks.
UPDATE (@Robbie’s code)
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;
}
}
The error said: exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected'.
ANSWER
Change:
... new PDO("".DB_DRIVER.":host=".DB_HOST.";db_name=".DB_NAME."", ...
into:
... new PDO("".DB_DRIVER.":host=".DB_HOST.";dbname=".DB_NAME."", ...
After catch the error message (from the updated code) and referring to this thread, I found that dbname part has written as dn_name on my code. So I change it into dbname and it works perfect! Thanks @Robbie for your code! 🙂
If it returns nothing, then it failed. You need to call the error functions (
errorInfo,errorCode) to find out why.But the tricky part is you don’t know if the error is on the database or the statement, so the best trick is to use exception error reporting, wrap all the functions in a try catch, and the exception, when trapped, will belong to either the DB or the statement. Much easier to handle.
Your code would be: