Php/Mysql - need help to insert and update multiple rows with a single query
is there any way how in this situation insert and update DB with single queries?
$message = 'Hello to all group members';
$userdata = mysql_query("SELECT memberid, membernick FROM members WHERE groupid='$cid'") or die('Error');
while(list($memberid, $membernick) = mysql_fetch_row($userdata)) {
$result1 = mysql_query("INSERT INTO messages VALUES (NULL,'$membernick', '$memberid', '$message')") or d开发者_StackOverflow社区ie('Error');
$result2 = mysql_query("UPDATE users SET new_messages=new_messages+1, total_messages=total_messages+1 WHERE id='$memberid'") or die('Error');
}
The update and insert can be one-ified with mysql >= 5.1. Try
$message = 'Hello to all group members';
$userdata = mysql_query("SELECT memberid, membernick FROM members WHERE groupid='$cid'") or die('Error');
$memberids = array();
$values = array();
while(list($memberid, $membernick) = mysql_fetch_row($userdata)) {
array_push($values, "(NULL,'$membernick', '$memberid', '$message')");
array_push($memberids, "'$memberid'");
}
// ==> replace colX with the names of your columns
// check http://dev.mysql.com/doc/refman/5.1/en/insert.html for further information
$result1 = mysql_query("INSERT INTO messages (col1,col2,col3,col4) VALUES ".implode(",", $values)) or die('Error');
$result2 = mysql_query("UPDATE users SET new_messages=new_messages+1, total_messages=total_messages+1 WHERE id IN (".implode(",", $memberids).")") or die('Error');
I Hope this will help Jerome Wagner
Nope, MySQL doesn't have a support for updating or inserting multiple rows in multiple tables with a single query.
精彩评论