【发布时间】:2016-05-31 19:10:52
【问题描述】:
我正在尝试将数组传递给SELECT * FROM table WHERE IN() 语句。我期待3个结果。但我得到了 2 个结果。
我在以下 2 个帖子中知道同样的问题
Can I bind an array to an IN() condition?
和
MySQL WHERE IN () + AND , PDO returns only one row
但是我仍在学习 php pdo,因此我对代码的理解不足以弄清楚如何将他们的代码重新用于我的代码。
希望有人能指出我哪里做错了。因为我从 select in 语句中得到了部分结果。我怀疑我没有正确地将数组传递到 IN() 中。
下面是我的控制页面的php代码
$customer_ids = array(1,2,3,4,5,6,7);
//in actual case I get array from another query.
$customer_id = implode(',',$customer_ids);
//add comma to the array
$template->orders = $rephome->getOrder($customer_id);
//passing the imploded array into my Model page with class named rephome,
//call on the method of getOrder, which is the select query
下面是我的模型页面。
public function getOrder($customer_id){
$this->db->query("SELECT * FROM orders WHERE customer_id_fk IN(.$customer_id.)");
$results = $this->db->resultset();
return $results;
以下是我的数据库类中的内容
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null) {
if (is_null ( $type )) {
switch (true) {
case is_int ( $value ) :
$type = PDO::PARAM_INT;
break;
case is_bool ( $value ) :
$type = PDO::PARAM_BOOL;
break;
case is_null ( $value ) :
$type = PDO::PARAM_NULL;
break;
default :
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue ( $param, $value, $type );
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}
【问题讨论】:
-
使用与数组中的项目一样多的占位符构建 PDO 字符串。用适当的值绑定每个占位符。
-
无论如何,“问题”是
".. IN(.$customer_id.)"导致.. IN(.1,2,3,4,5,6,7.)这是无效的SQL -.只是字符串中的文字。错误消息会说得这么多。 -
我想你刚刚解决了我的问题。通过删除点。我得到了正确的结果。