【问题标题】:How do I use pdo execute function to select table?如何使用 pdo 执行功能来选择表?
【发布时间】:2019-05-30 04:13:07
【问题描述】:

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 的兼容性问题,或者我做错了什么。

【问题讨论】:

  • 我建议先创建一个工作示例,而不是先将其包装在一个类中。您还应该阅读如何在进行查询时检查错误。 TBH,我宁愿推荐使用久经考验的 db-library 而不是自己构建。
  • 你应该使用已经存在的包装类而不是创建你自己的。您可以使用我的课程GrumpyPDO(显然我个人推荐),但还有更多类似的dozensifnothundreds。真的没有必要重新发明轮子

标签: php mysql oop pdo


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 2013-08-01
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多