PDO执行数组字符串转换错误 [英] PDO execute array to string conversion error

查看:272
本文介绍了PDO执行数组字符串转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个数组字符串转换错误,当我尝试运行PDO执行。的执行必须输入一个是正常串与其他的阵列。我的继承人code:

I am getting an array to string conversion error when I am trying to run a PDO execute. The execute has to inputs one being a normal string and the other an array. Heres my code:

$id = "1";    
$array = array("a",  "b",  "c");
$in  = str_repeat('?,', count($array) - 1) . '?';

$sql1 = "SELECT * FROM tbl1 AS tb1 RIGHT JOIN tbl2 AS tb2 ON (tb1.e_id = tb2.e_id)LEFT JOIN tbl3 AS tb3 ON (tb2.m_id = tb3.m_id) WHERE tb1.u_id = ? AND tb1.letters IN ($in)";


$statement1 = $db_handle->prepare($sql1);
$statement1->setFetchMode(PDO::FETCH_ASSOC);
$statement1->execute(array($id,$array));

$res = $statement1->fetchAll();

因此​​,执行行给我的字符串转换错误。我有我的打印阵列和问号,他们输出的罚款。 SQL语句还不错,我已经试过它的phpMyAdmin,这我没有使用正确的执行,但我不知道如何改变我已执行的方式工作得很好,那么清楚。

So the execute line gives me the string conversion error. I have printed my array and the question marks and they output fine. The sql statement is also fine, I have tried it on phpMyAdmin and it works just fine so clearly I am not using the execute properly but I am not sure how to change the way I have executed it.

有人能解释一下?

推荐答案

的execute()方法需要一个单一的阵列。从文档:

execute() method expects a single array. From the documentation:

执行prepared声明。如果prepared声明包含参数标记,则必须:

Execute the prepared statement. If the prepared statement included parameter markers, you must either:


      
  • (SNIP)

  •   
  • 通过输入唯一的参数值的数组

  •   

使用阵列($ ID,$阵列)你会传递一个多维数组,看起来像这样:

With array($id,$array) you'd be passing a multi-dimensional array that looks like this:

Array
(
    [0] => 1
    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

)

这当然不是什么期望。它需要被插入含有的值的一维数组。

This is certainly not what it expects. It needs a single-dimensional array containing the values to be inserted.

要解决这个问题,你必须修改阵列格式。该ID添加到阵列的开始,像这样:

To fix this issue, you have to modify the array format. Add the ID to the start of the array, like so:

$array = array(1, "a",  "b",  "c");

如果是动态生成的ID变量,那么你可以手动将其添加到阵列中开始使用 array_unshift()功能:

If the ID variable is generated dynamically, then you can manually add it to the array start using array_unshift() function:

$id = "1";    
$array = array("a",  "b",  "c");
$array = array_unshift($array, $id);

...然后修改的execute()调用像这样:

$statement1->execute($array);

这篇关于PDO执行数组字符串转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆