1

I want to update a MySQL database entry. For this, I am using a PHP form. I get entered data in form of an array (fieldname as key and data as value), and also the id of entry to be edited. But how do I update the entry by using the array?

I am using similar array for inserting new entry by using following code -

array_walk($register_data, 'array_sanitize');
$register_data['password'] = md5($register_data['password']);

$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';

mysql_query("INSERT INTO `users` ($fields) VALUES ($data)"); 

But how do I update an existing row?

2
  • See the red warning on top for mysql_* functions. If you are going to learn php, learn it the right way. Use PDO/mysqli functions. Commented Jan 26, 2015 at 6:23
  • This is just a quick fix. I will be doing everything in proper way, later. Thanks for the suggestions. Commented Jan 26, 2015 at 6:29

3 Answers 3

1

Try below :-

$arr = array('name' => 'kh', 'phone' => 23456);

$s = "UPDATE table_name SET ";

foreach($arr as $k => $v){
   $s .= $k."='". $v."', ";
}

$s = rtrim($s, ", ");

$s .= " where id = 1";

echo $s;

Output will be :-

UPDATE table_name SET name='kh', phone='23456' where id = 1

Sign up to request clarification or add additional context in comments.

Comments

0

Use an UPDATE query,

UPDATE (Table Name) set (Field name)= (New Value) where (your condition).

or

UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value;

1 Comment

I am aware of UPDATE query. I just can't figure out how to make it work with an array as input (see my INSERT example). I want to do it dynamically. So that any changes in the array will be reflected automatically in the query.
0
$userData = array();
foreach ($userList as $user) {
    $userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
 }
$query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);
mysql_query($query);

You can also do this for $fields.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.