php - 如何使用 pdo 执行功能来选择表?
问题描述
索引.php
<?php
require_once 'core/init.php';
DB::getInstance()->query("SELECT * FROM users");
在这堂课中,我使用的是单例模式,它已成功连接到数据库。
数据库文件
<?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';
}
}
}
}
现在的问题是,当我在其中传递 sql 查询时,query()
它属于 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()
or prepare()
or后检查错误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;
}
推荐阅读
- python-3.x - 嵌套循环和列表克隆
- sql - 从 reg_ex_split_table 输出中删除空白结果
- ruby - 从字符串制作时间戳
- git - 有没有办法将 Git 提取分成多个较小的提取?
- flutter - NoSuchMethodError:在 null 上调用了方法“查询”。(虽然它将项目带到 UI)
- html - 并排显示按钮而不是堆叠
- c++ - 使用 UINT32_MAX 的范围条件
- python - 来自 pycharm vs pip、python 3.8 的库
- github - 如何快速找到一个人的github句柄?
- azure-data-factory - 从数据工厂管道中的 ML Studio 管道中获取结果