tags:

views:

162

answers:

1

Hi all,
Here's what I'm trying to do: Update an arbitrary number of rows, changing several fields to the SAME value.

$var = "1 3 5 7 9";  
$query = "UPDATE tablename SET seen_before = 1 WHERE id = SET ($var);"

My question is this: What is the exact syntax on the Where clause when I lookin in a set, and how do I pass in the Set items through a php variable.

Thanks,
Michael

+6  A: 
$ids   = "1, 3, 5, 7, 9";  
$query = "UPDATE tablename SET seen_before = 1 WHERE id IN ($ids)";

If your IDs are dynamic, and they probably are, use something like this in order to properly escape them for an SQL query:

// Assuming $ids it's coming from an untrusted source, like $_GET
$ids   = array(1, 3, 5, 7, 9);
$ids   = array_map('intval', $ids);
$ids   = implode(', ', $ids);

$query = "UPDATE tablename SET seen_before = 1 WHERE id IN ($ids)";
Ionuț G. Stan
@Ionut: you need to fix either $ids or $var.
hobodave
Thanks @hobodave, fixed.
Ionuț G. Stan
Thanks, my input had to be 'trim'med.So does IN only work on a string?
Michael
@Michael, it works on many SQL types, but as long as you dynamically build the query with PHP, all you can do is building an SQL string, but this string will be interpreted as expected on the MySQL server.
Ionuț G. Stan