updating multiple rows in php/mysql - php

Below is code which I want to use to delete messages. I need not only to delete messages but also update total number of messages in "pmessages_folders" table.
Let's say, I want to delete messages with ids 3,4,5. Two of these messages are in the same folder:
message 3 -> folder 1
message 4 -> folder 2
message 5 - > folder 2
So, from folder 2 will be deleted 2 messages and I need to set total_messages for this folder -2 but query (result2) updates it only once. Itlooks that array_push ignores identical values.
Is there any way how to solve this problem?
Thanks.
$result = mysql_query("SELECT sender FROM messages
WHERE id IN(". implode(', ', $_POST['msg_id']).")") or die ('Error1');
$memberids = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($memberids, $row['sender']);
}
$result2 = mysql_query("update messages_folders set total_messages=total_messages-1
where sender IN (".implode(",", $memberids).") and recipient='$id'") or die('Error2');
$result3 = mysql_query("DELETE FROM messages
WHERE id IN (". implode(', ', $_POST['msg_id']).")")or die('Error3');
PART 2
Here are my changes:
$result = mysql_query("SELECT sender, COUNT(sender) FROM messages
WHERE id IN(". implode(', ', $_POST['msg_id']).") GROUP BY sender") or die ('Error');
while ($row = mysql_fetch_assoc($result)) {
$memberid = $row['sender'];
$number_to_delete = $row['COUNT(sender)'];
$my_array[] = array($memberid,$number_to_delete);
}
The result:
Array
(
[0] => Array
(
[0] => 893
[1] => 1
)
[1] => Array
(
[0] => 557
[1] => 3
)
)
So, $my_array[0] contains folder ID and $my_array[1] contains number of deleted messages.
Folder 893 should be updated: total_messages= total_messages-1
and
folder 557 should be updated: total_messages= total_messages-3
No idea how to do this with IMPLODE. I need something like this:
$result9 = mysql_query("update messages_folders set total_messages=total_messages-$my_array[1]
where sender $my_array[0] and recipient='$id'") or die('Error');
I am not running this query. It's just to show what I want to achieve.

The way you are currently doing it leads to a race condition if two people simultanously try and delete the same messages, the count could go off.
It is better to delete the messages, and then update the total to be equal to the count of the messages. I would need to see the structure of your tables in order to offer an example query

Instead of array_push(), use $memberids []= $row['sender'];
This is actually recommended by php.net: http://php.net/manual/en/function.array-push.php as it is equivalent and doesn't have the function overhead. Although array_push() shouldn't care about previous values.

Related

PHP SQL - Search for match with same players

Good mornin'.
I've been tryin to make "something" that will compare matchup percentage but i'm stuck'd at searching for matches with 2 same players.
I've found something about AND OR parenthesis so here is my sql query
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' OR playerName01 ='".$player2."') AND (playerName02 = '".$player2."' OR playerName02='".$player1."')";
$result3 = $db->query($ccc);
$ids = array();
while ($row55 = $result3->fetch_assoc())
{
$ids[] = $row55['winner'];
}
But , the problem is whenever i try to get data , it gives me more indexes than actualy expected.
This is the result of printing array values after fetching.
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
As expected is only 2 3 4 as u can see in the DB sample here.
db sample
Anyone suggestions on what i'm doing wrong?
A simple way to write this in MySQL uses tuples:
where (?, ?) in ( (playername01, playername02), (playername02, playername01) )
The ? are for parameters. That should be the way that you pass values into queries.
You are doing wrong while using AND OR in where clause
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' AND playerName02 ='".$player2."') OR (playerName01 = '".$player2."' AND playerName02='".$player1."')";
Try this #Patrik Dano

Encode JSON From MySQL Fetch Assoc & Fetch Array

I have this PHP syntax and works as I expected :
$sqldata = mysql_query("
SELECT FirstName, LastName, NumberOfChildren, SchoolTuition FROM User WHERE User.Username = '$Username' LIMIT 1;
");
$rows = array();
while($r = mysql_fetch_assoc($sqldata)) {
$rows[] = $r;
}
echo json_encode($rows);
now, the problem is I want to calculate total school tuition (NumberOfChildren * SchoolTuition) and it must be done before json_encode() function. and my client doesn't want to add one extra column on their database.
so I must calculate this TOTAL School Tuition using PHP and put it back on $rows array as latest value of array before json_encode.
I tried calculate using mysql_fetch_array first to get $rows[2] and $rows[3], but since I already use mysql_fetch_assoc before, this mysql_fetch_array won't work.
last thing, I mysql_fetch_assoc generates 2 dimensional array. because when I use print_r($rows), I see this :
Array ( [0] => Array ( [FirstName] => Mary [LastName] => Smith [NumberOfChildren] => 3 [SchoolTuition] => 2000 ) )
while array_push function only used to push 1 dimensional array, right?
please kindly give me solution of this problem. thank you very much.
You can just do the calculation in SQL, without having to add the column.
SELECT FirstName, LastName, NumberOfChildren, SchoolTuition,
(NumberOfChildren * SchoolTuiton) AS TotalSchoolTuiton
FROM User WHERE User.Username = '$Username' LIMIT 1
SELECT FirstName, LastName, NumberOfChildren, SchoolTuition, NumberOfChildren*SchoolTuition AS TotalTuition FROM User WHERE User.Username = '$Username' LIMIT 1;

MySQL Query only grabbing one row instead of multiple. Why?

I'm trying to grab multiple rows via these lines from the MySQL database:
$msg_sql = "SELECT * FROM ".TABLE_PREFIX."quotes ORDER BY rand(curdate()) LIMIT 3";
$msg_res = mysqli_fetch_assoc(mysqli_query($link, $msg_sql));
print_r($msg_res);
However, I only get 1 row back. Which is:
Array ( [id] => 1 [message] => test_message [Link] => link here )
I wish to get multiple rows (so multiple ID's)
Please tell me what I'm doing wrong. I'm still new to MySQL.
You must loop once for each row you fetch.
$result = mysqli_query($link, $msg_sql);
while ($item = mysqli_fetch_assoc($result)) {
print_r($item);
}
You need to loop through your results:
$results = mysqli_query($link, $msg_sql);
while ($msg_res = mysqli_fetch_assoc($results))
{
print_r($msg_res);
}

How to mysql_query from same table with different where clause in same php file

I have a table containing 4 articles with id 1,2,3 and 4 as well as ordering value 1,2,3,4.
They have separate columns for their title, image etc. I need to get them distinctly with where clause. So i did:
For article 1:
//topstory1
$sql_topstory1 ="SELECT * FROM topstory WHERE story_active='1' && story_order='1'";
$result_topstory1 = mysql_query($sql_topstory1);
$row_topstory1 = mysql_fetch_array($result_topstory1);
$story1_title = $row_topstory1['story_title'];
$story1_abstract = $row_topstory1['story_text'];
And for article 2
//topstory2
$sql_topstory2 ="SELECT * FROM topstory WHERE story_active='1' && story_order='2'";
$result_topstory2 = mysql_query($sql_topstory2);
$row_topstory2 = mysql_fetch_array($result_topstory2);
$story2_title = $row_topstory2['story_title'];
$story2_abstract = $row_topstory2['story_text'];
As I have to reuse them in a page.
PROBLEM IS, the first query works but the second one doesn't. It seems like MySql cannot execute two consecutive queries on the same table in a single php file. But I think there is a simple solution to this...
Please help me soon :( Love you guys :)
There are several possible reasons for the second query to fail, but the fact that it's the second query in the file does not cause it to fail.
I would expect that article 2 does not have the active flag set to 1, causing you to get an empty result set.
Another option is that you may have closed the mysql connection after the first query, then you can't execute another query. (General rule: don't close database connections. PHP takes care of that.)
Why not just get them both with 1 query?
$sql_topstory ="SELECT * FROM topstory WHERE story_active='1' && story_order IN(1, 2) ORDER BY story_order DESC";
$result_topstory = mysql_query($sql_topstory) or trigger_error('Query Failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result_topstory)) {
$title[] = $row['story_title'];
$abstract[] = $row['story_abstract'];
}
// Then to display
echo 'Story 1 is ' . $title[0] . ' with an abstract of ' . $abstract[1];
There are plenty of ways to do this, this is just a simple demonstration.
$query = <<<SQL
SELECT
story_title
, story_text
FROM
topstory
WHERE
story_active
ORDER BY
story_order ASC
SQL;
$result = mysql_query($query);
$stories = array();
while ($row = mysql_fetch_assoc($result)) {
$stories[] = $row;
}
Now you have an array of stories like so:
array(
0 => array(
'story_title' => ?
, 'story_text' => ?
)
, 1 => array(
'story_title' => ?
, 'story_text' => ?
)
)
Should be pretty easy to iterate through.

Why returns the first element of an array only?

$count =0;
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");
$result4= mysql_fetch_array($result3);
print $result4[$count].'<br>';
$count++;
}
mysql_free_result($result1);
mysql_free_result($result3);
Let's have a look at how mysql_fetch_array works - for example if you have table structure like
id | name | surname | role
1 John Smith user
2 Peter Qeep user
3 Mark Ziii admin
When you execute a query SELECT * FROM table and then loop $result = mysql_fetch_array($query), $result will always be an array(4) containing
[0] => id,
[1] => name,
[2] => surname,
[3] => role
Therefore, when you execute the query $result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");, in the first iteration, $count will be 0 which is the key for the result returned by the previous query, however in any further iteration it will increase and that will lead to an undefined key. This means that you have to stop using the variable $count and just use $result2[0] instead.
Also, way better approach to this would be using MySQL JOIN, in your example it would be SELECT w.fsyn FROM sbsw s JOIN wrsyn w ON s.fwid = w.fwid WHERE s.fword = "'.$searchText.'";
Please, use reasonable variable names and indent properly. You're getting one column from each row as you're only printing out once for each iteration over your rows.
Basically: For each row, print the value of a column.
The $count-variable decided which column, but it obviously didn't make sense at it counts the row you're at.
Something like this should do it: (not tested)
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2['fwid']."'");
$result4= mysql_fetch_row($result3);
for($x = 0; $x < count($result4); $x++){
print $result4[$x].'<br>';
}
}
mysql_free_result($result1);
mysql_free_result($result3);
Oh and I changed fetch_array to fetch_row in the inner loop to ease iteration.

Categories