index.php
<?php
require_once 'core/init.php';
DB::getInstance()->query("SELECT * FROM users");
在这个类中,我使用单例模式,它已成功与数据库连接。
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') .';db='.Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
//echo "Connected";
}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){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
// echo 'prepared statement';
if($this->_query->execute()){
echo 'do query';
}else{
echo 'did not execute';
}
}
}
}
现在的问题是,当我在 query()
中传递 sql 查询时,它处于 else 条件“未执行”。所以我的问题是为什么它不执行。 pdo 与 mysql db 之间是否存在兼容性问题,或者我做错了什么。
最佳答案
我总是启用 PDO 异常。如果查询或对 PDO 函数的任何其他调用出现问题,它将引发包含错误消息的异常。
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
(您只需设置一次,通常是在创建 PDO 连接后立即设置。)
参见http://php.net/manual/en/pdo.error-handling.php
如果您不想使用异常,则应在每次调用 query()
或 prepare()
后检查错误或execute()
,并将它们输出到错误日志中。
$this->_query = $this->_pdo->prepare($sql);
if ($this->_query === false) {
$this->_error = $this->_pdo->errorInfo();
error_log("Error '{$this->_error[2]}' when preparing SQL: {$sql}");
return false;
}
$ok = $this->_query->execute();
if ($ok === false) {
$this->_error = $this->_query->errorInfo();
error_log("Error '{$this->_error[2]}' when executing SQL: {$sql}");
return false;
}
关于php - 如何使用pdo执行函数来选择表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54024545/