Why is this MySQL query slowing down my code - php

Currently I have a MySQL query I run in PHP and when going through the results I update the original table but a simple table with 500 rows takes 30 seconds to complete:
$sqlquery = mysql_query('SELECT id, special_data FROM stats_visits WHERE processed = 0');
while($row = mysql_fetch_assoc($sqlquery)){
$stat_id = $row['id'];
// Make use of special_data field for some operations
mysql_query('UPDATE stats_visits SET processed = 1 WHERE id = ' . $stat_id);
}
Is it because I am updating the table from which I am selecting? I've solved this by doing the following but because the table might have thousands of records in future I'm unsure how well the IN will hold up:
$statids = array();
$sqlquery = mysql_query('SELECT id, special_data FROM stats_visits WHERE processed = 0');
while($row = mysql_fetch_assoc($sqlquery)){
$statids[] = $row['id'];
// Make use of special_data field for some operations
}
mysql_query('UPDATE stats_visits SET processed = 1 WHERE id IN(' . implode(',', $statids) . ')');

If all you want is to update all the records to being processed = 1 Why not resolve it with a single query?:
UPDATE `stats_visits` SET `processed` = 1 WHERE `processed` = 0;

In the first version you're hitting the database once for every single update. This is normally a bad idea. The 2nd version is hitting the database once.
If you are concerned about how this will work out in the future, perhaps create a hybrid. Batch the updates up into groups of 100 and update them in blocks.

The easiest way would be to store all of the ids which need updating as an array then implode these into the query with the IN operator.
e.g.
$processedArray= array();
while($row = mysql_fetch_assoc($sqlquery)){
$stat_id = $row['id'];
//Your processing goes here
$processedArray[] = $stat_id; //Store an id if it needs updating as processed
}
mysql_query('UPDATE stats_visits SET processed = 1 WHERE id IN ('.implode(',', $processedArray).')');

Related

add one (+1) to a field in mysql database using php

I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.

Database Insert into Random Unused Row - With Transaction

I am writing an app that wishes to randomly assign a number to users, then puts in into a MySql database. There are many people who use it at the same time and as such I dont want parallel uses to overwite each other.
My current code is the following:
$sql_get = "SELECT * FROM database";
$results = mysql_query($sql_get, $bd);
$list = array();
while($row = mysql_fetch_array($results))
{
if ($row['userId'] == "")
{
array_push($list, $row['number']);
}
}
$rand_nums = array_rand($list , 1);
$sql_update = "UPDATE database SET userId='". $userId ."' WHERE number=". $rand_nums;
$results = mysql_query($sql_update, $bd);
So basically, it gets the empty rows, puts them into a list, chooses a random empty row number and puts the data into the row. The current issue is that the get and the empty rows can happen at the same time for multiple users and may overwrite data written at the same time.
How can I structure this code (transaction or otherwise) to ensure concurrent use has no bad effects?
Thank you
You could do it all in one query:
UPDATE database AS d
SET d.userId = $userId
WHERE d.userId = ''
ORDER BY RAND()
LIMIT 1

echo updated values instead of old values

How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}

how UPDATE mysql row plus one and get the value

I updated with success
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
but how can I get the "queue2" value without opening a new request to MySQL
I can simply get the new value with this command
$selresult = mysql_query("SELECT * FROM $table WHERE `id` = '$getid'") or die(mysql_error());
but I'm afraid that the database can get new update again and i will get higher number
Any idea how to do it ?
you can use query to update the value.
mysql_query("UPDATE user_profile SET userpoints = userpoints + 1 WHERE user_id = '".$user_id."'");
See URL:-
PHP + MySQL transactions examples
Try this:-
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
You will need to use a transaction between the queries to be certain.
The docs for transactions are here. A good SO question that covers it in detail: PHP + MySQL transactions examples
Edit:
Looking at it from a different angle, why don't you do it in reverse though? It might save the need for a transaction (thought it is possible that you get multiple reads before a write):
Get the value for your queue2 value to display in the page from this:
mysql_query("SELECT * FROM $table WHERE `id` = '$getid'");
You have the true value now, so you can run:
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
No transaction and you know the value of the data before the update.

Setting status of other rows after INSERT

Hey, I have a field called STATUS and it is either 1 to show or 0 to hide. My code is below. I am using an edit in place editor with jQuery. Everytime you update it creates a new ROW which I want, but I want only the new one to have STATUS = 1 and the others to 0. Any ideas on how I would do that?
<?php
include "../../inc/config.inc.php";
$temp = explode("_", $_REQUEST['element_id'] );
$field = $temp[0];
$id = $temp[1];
$textboxval = stripslashes(mysql_real_escape_string(preg_replace('/[\$]/',"",$_REQUEST["update_value"])));
$query = "INSERT INTO notes ($field,status,date,c_id) VALUES ('$textboxval','1',NOW(),'$id')";
mysql_query($query);
echo($_REQUEST['update_value']);
?>
I am not sure exactly what you mean - do you want to make all the entries except the new one have status = 0? If so, just issue an update before the insert:
UPDATE notes SET status = 0
However, I should also note that you have a potential SQL injection to worry about. By stripping slashes after applying "mysql real escape string", you are potentially allowing someone to put text in your SQL statement that will execute an arbitrary SQL statement.
Something like this, sorry for the post before, I mis read it the first time then went back:
<?php
include "../../inc/config.inc.php";
$temp = explode("_", $_REQUEST['element_id'] );
$field = $temp[0];
$id = $temp[1];
$textboxval = mysql_real_escape_stringstripslashes((preg_replace('/[\$]/',"",$_REQUEST["update_value"])));
// set older entries to 0 - to not show but show in history
$hide_notes = "UPDATE notes SET status = 0";
mysql_query($hide_notes);
// add new entry with status of 1 to show only latest note
$query = "INSERT INTO notes ($field,status,date,c_id) VALUES ('$textboxval','1',NOW(),'$id')";
mysql_query($query);
echo($_REQUEST['update_value']);
?>
i just ran in to a problem I didn't of the set up of my table doesn't allow me to show more than one client a time and i will be having numerous clients, my bad on planning ha
You really want to get the ID of the newly generated row and then trigger an UPDATE where you all rows where the ID is not the new row, e.g.
UPDATE notes SET status = 0 WHERE id != $newly_generated_id
If the ID column in your table is using AUTO_INCREMENT you can get its ID via "SELECT LAST_INSERT_ID()" and then use the return value in that statement in your UPDATE statement.
Pseudo code:
$insert = mysql_query("INSERT INTO ...");
$last_id = mysql_query("SELECT LAST_INSERT_ID()");
$update = mysql_quqery("UPDATE notes SET status = 0 WHERE id != $last_id");
The only caveat to this approach is where you might have a brief moment in time where 2 rows have status=1 (the time between your INSERT and the UPDATE). I would wrap all of this in a transaction to make the whole unit more atomic.

Categories