tags:

views:

113

answers:

2

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

}
A: 

Nope, MySQL doesn't have a support for updating or inserting multiple rows in multiple tables with a single query.

Ondrej Slinták
well, that certainly is not true; a simple `UPDATE Users SET UserName='NewUser'` would update all rows in a single query.
Marek Karbarz
Yes, but original poster is asking if he can insert _and_ update DB with a single query. I'm going to update my answer, so it's not confusing.
Ondrej Slinták
Ondrej, my question was not accurate. Actually, I wanted to ask if it's possible to insert multiple rows with a single query and to update multiple rows with a single query. I don't need such a query which inserts and updates data at the same time. Thanks to Jerome Wagner - he answered my question.
Guanche
Don't forget to mark Jerome's answer as correct ;)
Ondrej Slinták
+1  A: 

Hello, 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

Jerome WAGNER
He wanted to update / insert multiple rows with a _single_ query, which isn't possible with MySQL.
Ondrej Slinták
No I think he wants to avoid having a number of request that grows with the number of members. Shrinking the code to 2 requests seems ok to me.
Jerome WAGNER
Jerome Wagner, thank you very much. That's what I needed. It works!
Guanche