Web lists-archives.com

Re: [PHP] Array to string conversion error help needed




On 08/03/16 18:56, dealtek@xxxxxxxxx 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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php