gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:37:41 25 4
gpt4 key购买 nike

在这种情况下,有什么办法可以用单个查询插入和更新数据库吗?

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

}

最佳答案

更新和插入可以与 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');

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

关于Php/Mysql - 需要帮助以通过单个查询插入和更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2571525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com