Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.