Php / Mysql - 需要帮助才能通过单个查询插入和更新多行

时间:2010-04-03 14:38:55

标签: php mysql

有什么办法在这种情况下如何使用单个查询插入和更新数据库?

$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 die('Error');
$result2 = mysql_query("UPDATE users SET new_messages=new_messages+1, total_messages=total_messages+1 WHERE id='$memberid'") or die('Error');

}

2 个答案:

答案 0 :(得分:2)

更新和插入可以与mysql> = 5.1一起使用。尝试

$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');

我希望这会有所帮助 杰罗姆瓦格纳

答案 1 :(得分:0)

不,MySQL不支持使用单个查询在多个表中更新或插入多行。