首页 > 解决方案 > 如何使用 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 的兼容性问题,或者我做错了什么。

标签: phpmysqlooppdo

解决方案


我总是启用 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;
}

推荐阅读