Reputation: 363
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?
Upvotes: 1
Views: 2669
Reputation: 1817
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
Upvotes: 1
Reputation: 2339
$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.
Upvotes: 0
Reputation: 345
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;
Upvotes: 0