just wondering whether there is any best practice or or the like for following:
I select a set data (couple thousend of rows) and depending on the values of two fields i have to update a third field (or not).
two ways to achieve this are imho (pseudo code) :
PHP Code:
SELECT id
, field1
, field2
FROM table
foreach ($result as $r)
{
if ($r->field1 == '1' || $r->field2 == '1')
{
UPDATE table
SET field3 = '1'
WHERE id = $r->id
}
else
{
UPDATE table
SET field3 = '0'
WHERE id = $r->id
}
}
or, as alternative:
PHP Code:
// same select query
$is_avail = '';
$no_avail = '';
// create comma-separated lists
foreach ($result as $r)
{
if ($r->field1 == '1' || $r->field2 == '1')
{
$is_avail .= ",". $r->id;
}
else
{
$no_avail .= ",". $r->id;
}
}
// removing the first comma
$clause_is_avail = substr($is avail, 1);
$clause_no_avail = substr($no avail, 1);
// updating the fields
UPDATE table
SET field3 = '1'
WHERE id
IN ($clause_is_avail)
UPDATE table
SET field3 = '0'
WHERE id
IN ($clause_no_avail)
for sure, the first example is more readable but what's the 'better' way to handle this?
Bookmarks