Dirk
Dirk

Reputation: 6884

Update Multiple Rows Mysql from php

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

Upvotes: 1

Views: 669

Answers (1)

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179119

$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)";

Upvotes: 6

Related Questions