Jump to content

UPDATE syntax in FOR loop


pets2soul

Recommended Posts

Dear experts,

 

I'm working on a user info updating form, and I only want the amended fields to be updated to the database, I figured this part out, however what caught me is the updating part, where my amended values are stored in an array, and I'm trying to put the values into the SET part with the use of FOR loop, but I can't get the query to work properly...it'd be super duper thankful if anyone can help me with it. Below is my code:

 

	$diff_num = count($diff_info);
$diff_value = array_values($diff_info);
$diff_key = array_keys($diff_info);

for($i = 0; $i < $diff_num; $i++)
{
	$db_update = "AND " . $diff_key[$i] . " = '" . $diff_value[$i] . "' ";
	$query = "UPDATE db_table SET field_one = '$value_one' " . $db_update . " WHERE field_some = '$value_some'";
	if (mysql_query($query))
	{
	return true;
	} else {
	return false;
	}
}

Link to comment
https://forums.phpfreaks.com/topic/230794-update-syntax-in-for-loop/
Share on other sites

Hi

 

No need to split the array and then do a for loop. You can just use foreach

 

<?php

if (count($diff_info) > 0)
{
$db_update = '';
foreach($diff_info AS $diff_key=>$diff_value)
{
	$db_update .= ", $diff_key = '" . mysql_real_escape_string($diff_value) . "' ";
} 
$query = "UPDATE db_table SET field_one = '$value_one' " . $db_update . " WHERE field_some = '$value_some'";
if (mysql_query($query))
{
	return true;
} 
else 
{
	return false;
}
}
return false; // nothing to update!

?>

 

Something like that should do it

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.