Re: Array to string conversion error help needed
| From: | Lester Caine | Date: | Tue, 08 Mar 2016 19:14:32 +0000 |
| Subject: | Re: Array to string conversion error help needed | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-325451@lists.php.net to get a copy of this message | ||
On 08/03/16 18:56, dealtek@gmail.com wrote:
> newbie mysql select help needed.
> this works fine...
> $sth = $pdo->prepare("SELECT * FROM table1 where id IN (1,2,3)"
>
> but with an array like...
>
> $mylist = array("1","2","3");
> or
> $mylist = array(1,2,3);
>
> these fail...
> $sth = $pdo->prepare("SELECT * FROM table1 where id IN $mylist"
> or
> $sth = $pdo->prepare("SELECT * FROM table1 where id IN ($mylist)"
>
> I get error : Array to string conversion...
> Q: Can anyone help me fix this?
The answer is in the error message ;)
You need to create $mylist as a string, so
$mylist = "(1,2,3)"; on the first line, but
$mylist = "1,2,3"; using the second line style is a little tidier.
If you have the values as an array, then the array needs to be
reformatted and one can use implode(",",$mylist), but one of the reasons
for using 'PDO' is so you can use the prepared queries with different
variables.
For example
$sth = $pdo->prepare("SELECT * FROM table1 where id IN ( ?,?,? );
$result = $sth->execute($mylist);
http://php.net/manual/en/pdostatement.execute.php
gives a lot more examples.
--
Lester Caine - G8HFL
-----------------------------
Contact - http://lsces.co.uk/wiki/?page=contact
L.S.Caine Electronic Services - http://lsces.co.uk
EnquirySolve - http://enquirysolve.com/
Model Engineers Digital Workshop - http://medw.co.uk
Rainbow Digital Media - http://rainbowdigitalmedia.co.uk