Re: Using an array(-ish) in SQL queries
| From: | (Jennifer Goodie) | Date: | Wed, 03 Nov 2004 01:37:04 +0000 |
| Subject: | Re: Using an array(-ish) in SQL queries | ||
| Groups: | php.db | ||
| Request: | Send a blank email to php-db+get-37164@lists.php.net to get a copy of this message | ||
-------------- Original message ----------------------
From: -{ Rene Brehmer }- <metalbunny@metalbunny.net>
> Task at hand: deleting or selecting (same difference) several numbers of
> records using only 1 query.
>
> My first version simply looped through all the ticked off IDs and ran a
> single query for each delete routine. I've still not suceeded in getting
> the delete queries to work on multiple tables at once, despite the column
> names being the same. But besides this:
Multi-table deletes are new to mySQL 4.0, so if you are running a 3.x release they won't work.
http://dev.mysql.com/doc/mysql/en/DELETE.html
>
> My current version generates, for multi-select cases, queries like this:
>
> DELETE FROM the_table WHERE
ID='1' OR
> ID='2' OR ID='3' OR
> ID`='4' OR
> ID='5' OR
> ID='6'
>
> or similar with the SELECT statement.
[snip lots of stuff]
> DELETE FROM the_table WHERE ID ISIN(1,2,3,4,5,6)
use IN http://dev.mysql.com/doc/mysql/en/Comparison_Operators.html#IDX1268
If you know all the values in the array are escaped and safe you can just use implode() to make the
list for IN
$string = implode("','",$array);
$sql = "SELECT FROM $table WHERE col_name IN('$string')";
Notice I added single quotes around the string, that is because they will be missing since implode
only sticks the string between array elements.
However, you'd need a join that makes sense for a multi-table delete. I don't know if it
will work with a union, I have never tried, maybe somone else will chime in.