Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用pdo execute函数选择表?_Php_Mysql_Oop_Pdo - Fatal编程技术网

Php 如何使用pdo execute函数选择表?

Php 如何使用pdo execute函数选择表?,php,mysql,oop,pdo,Php,Mysql,Oop,Pdo,index.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 __construc

index.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';
       }
    }
  }
 }

我总是启用PDO异常。如果查询或对PDO函数的任何其他调用出现问题,它将抛出包含错误消息的异常

$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
(您只需设置一次,通常在创建PDO连接后立即设置。)

如果不想使用异常,则应在每次调用
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;
}

你仔细看看这里了吗?或者在这里,我建议从制作一个工作示例开始,而不要先在类中包装它。您还应该了解如何在进行查询时检查错误。TBH,我建议您使用经过测试的db库,而不是构建自己的db库。您应该使用已经存在的包装类,而不是创建自己的包装类。你可以使用我的课程(显然我个人推荐),但还有更多类似的课程。真的没有必要重新发明轮子,我认为
$ok=$this->\u query->execute
没有返回布尔逻辑。如果
没有变为false,并且没有显示错误日志,则第二个
。即使我删除了我的
try catch
块,也会在ConstructUCutor中执行