【问题标题】:Sql query using pdo in mysql在mysql中使用pdo进行sql查询
【发布时间】:2014-08-02 11:25:38
【问题描述】:

我有一个使用 pdo 的非常简单的选择查询,但它不起作用。

通用的sql查询是

$sql = "select * from table where type != 'address' and type != 'multipleimage'";

现在在 pdo 我有

$fieldtype = array('address','multipleimage');
             $query = $this->db->prepare("SELECT * from table where 
(type not in $type) and (userid !=:userid) ");

$query->execute(array(':userid' => 2, $fieldtype ));

现在收到通知+警告

注意是'数组到字符串的转换......' 警告是“警告:PDOStatement::execute(): SQLSTATE[42000]: 语法错误或访问冲突.....”

【问题讨论】:

  • 你不能在一个数组中有两次相同的键,因为array(':type' => 'address', ':type' => 'multipleimage') 的结果是array(':type' => 'multipleimage')。而在像?:name 这样的PDO 占位符中,只接受primitive 值(字符串、数字等),而不接受像数组这样的复杂对象。 PDO 中没有任何东西会神奇地为您创建ANDOR 条件。
  • 如果这些值是硬编码的,准备好的语句有点矫枉过正。
  • 我已经用我在执行中使用的数组编辑了问题,但我认为格式错误。

标签: php mysql sql pdo


【解决方案1】:

为什么不使用 NOT IN 子句:

$sql = "select * from table where type not in ('address','multipleimage')";

像这样,你可能需要做一些小改动

<?php
$fieldtype = array('address','multipleimage');
$inQuery = implode(',', array_fill(0, count($fieldtype), '?'));

$db = new PDO(...);
$stmt = $db->prepare(
    'select * from table where type not in(' . $inQuery . ')'
);

// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
    $stmt->bindValue(($k+1), $fieldtype);

$stmt->execute();
?>

【讨论】:

  • 你可以有这个参考:stackoverflow.com/questions/920353/…
  • 我应该更改问题,因为我几乎没有其他参数。我按照链接并试图实现该数组的东西但没有工作。
  • 应该,是的,请编辑问题并添加错误(如果有)
  • 已解决..:)..非常感谢 Avishek
【解决方案2】:

我创建了自己的 ORM 类,名为 DBConnection.php。它为指定数据库中的任何表执行所有 CRUD 功能。它也使用 PDO。如果您愿意,请随意使用它、自定义并在您的代码中使用......


<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DBConnection
 *
 * @author alemayehu
 */
require_once '../lib/PHPDebug.php';

class DBConnection {
    private static $_instance = null;
    private $_pdo;
    private $_query;
    private $_error = false;
    private $_results;
    private $_count = 0;

    private function __construct() {
        try{
            $this->_pdo = new PDO("mysql:host=".Config::get("mysql/host").";dbname=".Config::get("mysql/db"),
                    Config::get("mysql/username"),Config::get("mysql/password"));

        } catch (Exception $ex) {
            PHPDebug::printLogText("Connection Failed : ". $ex->getMessage() , "../lib/debug.txt");
            die($ex->getMessage());
        }
    }

    public static function getInstance(){
        if(!isset(self::$_instance)){
            self::$_instance = new DBConnection();
        }
        return self::$_instance;
    }

    public function fetchResultSet($sql, $params = array()){
        //var_dump($params);passed
        $this-> _error = false;
        if($this-> _query = $this->_pdo->prepare($sql)){
            $x = 1;
            if(count($params)){
                foreach($params as $param){
                    $this->_query->bindValue($x, $param);
                    $x++;
                }

            }else{
                echo 'something wrong with the array';
            }

            var_dump($this->_query);

            if($this->_query->execute()){
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
            }else{
                $this->_error = true;
            }
        }
        return $this->_results;
    }

    public function query($sql, $params = array()){
        $this-> _error = false;
        if($this-> _query = $this->_pdo->prepare($sql)){
            $x = 1;
            if(count($params)){
                foreach($params as $param){
                    $this->_query->bindValue($x, $param);
                    $x++;
                }
            }

            if($this->_query->execute()){
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
            }else{
                $this->_error = true;
            }
        }
        return $this;
    }

    public function error(){
        return $this->_error;
    }

    private function action($action, $table, $where = array()){
        if(count($where) === 3){
            $operators = array('=', '<', '>', '<=', '>=');

            $field = $where[0];
            $operator = $where[1];
            $value = $where[2];

            if(in_array($operator, $operators)){
                $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
                if( !$this->query($sql, array($value))->error() ){
                    return $this;//was this
                }
            }
        }
    }

    public function get($table, $where){
        return $this->action('SELECT *', $table, $where);
    }

    public function delete($table, $where){
        return $this->action('DELETE', $table, $where);
    }

    public function insert($table, $fields = array()){
        if(count($fields)){
            $keys = array_keys($fields);
            $values = '';
            $x = 1;

            foreach($fields as $field){
                $values .= '?';
                if($x < count($fields)){
                    $values .= ', ';
                }
                $x++;
            }

            $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES( {$values} )";
            //var_dump($sql);
            if( ! $this->query($sql, $fields)->error()){
                return true;
            }
        }
        return false;
    }

    public function update($table, $id, $fields){
        $set = '';
        $x = 1;

        foreach ($fields as $name => $value) {
            $set .= "{$name} = ?";
            if($x < count($fields)){
                $set .= ', ';
            }
            $x++;
        }

        $sql = "UPDATE {$table} SET {$set} WHERE user_id = {$id}";


        if(! $this->query($sql, $fields)->error()){            
            return true;
        }else{
            return false;
        }

    }

    public function fetchAllRecords($table, $where){
        return $this->query("SELECT * FROM {$table} WHERE $where");
    }

    public function count(){        
        return $this->_count;
    }

    public function getResults(){
        return $this->_results;
    }

    public function first(){
        return $this->_results[0];
    }

}//end class

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多