MySQLi Update is not working properly - php

I am trying to update one of my row with PHP using MySQLi and if I refresh PHPMyAdmin less than 1 second after update it's sucessfull but if I only check the data 2 seconds+ after the update it doesn't update.
For exemple:
'UPDATE orders SET MachineID = '.$id.' WHERE OrderID = '.$OrderID.
'AND ProductID = '.$ProductID
Does not work unless I refresh quickly but...
'UPDATE orders SET MachineID = 2 WHERE OrderID = 4 AND ProductID = 12'
Will work no matter how long after I refresh. (Those are the data I normaly use to test.)
So I though it would be my variables, but I'm using them almost 10 times before this part of the code in other queries and it works perfectly.
I tried to trim() the variable and it did not help.
I also tried to use mysqli_real_escape_string() with no success.
mysqli_error() is not giving me anything.
mysqli_affected_rows() is giving me "1" which is what it is suppose to be.
And the weird part is if I execute 'SELECT MachineID FROM orders WHERE OrderID = 4 AND ProductID = 12', it gives me the updated answer even if phpMyAdmin does not update the data.
There is no other code after this, so nothing that could "reverse" the update.
A normal "test" ouput looks like this:
Edit: This it what the browser outputs.
ID: "2" //$id
OrderID: "4" //$OrderID
ProductID: "12" //$ProductID
UPDATE orders SET MachineID = 2 WHERE OrderID = 4 AND ProductID = 12 //Query
boolean true //Result var_dump
1 //Number of rows affected
2 //Machine ID
Note: The quotes are not part of the variables.
Edit: This is the PHP code
$query = 'UPDATE orders SET MachineID = '.$id.' WHERE OrderID = '.$OrderID.' AND ProductID = '.$ProductID;
echo 'ID: "'.$id.'"<br/>
OrderID: "'.$OrderID.'"<br/>
ProductID: "'.$ProductID.'"<br/>'.$query.'<br/>';
$res = $db->query($query);
var_dump($res);
echo mysqli_affected_rows ($db).'<br/>';
$result = $db->query('SELECT MachineID FROM orders WHERE OrderID = 4 AND ProductID = 12');
$result = $result->fetch_array();
echo $result[0];
I really don't understand why it would work in the file and after a quick refresh but not if it takes to long to retreive the data. It's like it would reset after a certain amount of time if it's not fetch.
I've been working on this for almost 2 days now I have no idea why it's not working. This is some pretty simple SQL query.
Edit: I've look into MySQL binary logs and it seems that I'm updating it back to 1 every time. The only way this could be happening is if the file would run twice, but if it runs twice why would the output be there only once ?
Edit: Ok, so it seems like the problem comes from Google Chrome. I've tested it on IE and it works. For some reason Chrome would be running the file twice.

Ok so I was able to find the problem and fix it.
Problem:
The problem was the famous "favicon" bug with Chrome which is trying to get the icon even if it doesn't exist, therefore the file is called twice.
Fix:
Since this file was meant to be called through an Ajax call the bug is not triggered since Chrome will not try to look for the "favicon". I basicly fixed the bug by testing it how it was supposed to be run and not just testing the file itself.

Related

Moodle no value in table but the query result count returns 1

I am using Moodle 2.9.1. I have a query to fetch the last record from the table:
My query as follows:
$qstndetails = $DB->get_record_sql('SELECT * FROM {epoll_questions} WHERE status=? AND courseid=? ORDER BY id DESC LIMIT 0,1',array(2,$curseId));
I am taking the count as
echo count($qstndetails);
I am getting the count as 1 in the case of result is there.
But in the case of result is not there also I am getting count as 1.
I had tried print_r($qstndetails) but nothing showing. But the count show as 1.
The expecting count is 0 when there is no result.
Why I am getting like this?
When developing, always have debugging switched on. This would probably have displayed an error message for the first code. Go to site admin -> development -> debugging, then debug messages = developer and switch on display debug messages.
Also LIMIT isn't an SQL standard. Moodle works with several databases so try to keep the SQL generic.
Also I would suggest using named parameters rather than ?. It makes the code easier to read but they can also be used in any order.
and finally, you can use IGNORE_MULTIPLE to get the first record.
So the code should be something like this:
$sql = "SELECT *
FROM {epoll_questions}
WHERE status = :status
AND courseid = :courseid
ORDER BY id DESC";
$params = array('status' => 2, 'courseid' => $curseid);
$qstndetails = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE);
Need to change the query to
$qstndetails = $DB->get_records_sql('SELECT * FROM {epoll_questions} WHERE status=? AND courseid=? ORDER BY id DESC LIMIT 0,1',array(2,$curseId));
Now working!!

MySQL Update will only update some fields specified in the query

I have a very simple query which updates a 'status', a 'has_note', (both are tinyints in the database) and a time. The time updates correctly every time this is run, however, the other two are not affected and never changed.
Here is the code:
$status_sql = "
UPDATE voe_employment
SET status = 5, email_date = NOW()
WHERE emp_id = " . $_POST['emp_id'] . "
LIMIT 1";
$status_result = mysql_query($status_sql);
I have copied and pasted the resulting $status_sql into pmadmin, and everything updates correctly.
Also, $status_result = 1 after executing this code, which signifies success.
This block of code is wrapped around a "try, catch" statement, and the catch is never run/activated. And I have tried wrapping the table name in ``, wrapping the 5 in '', etc.
Check to make sure no other code is doing another UPDATE right after. We have found this in the past. Another unexpected update was running that we didn't know was that overwrote the data.

Random jump within while() loop in PHP for MySQL query

I am doing an example project for University and got a problem that I can't solve.
In general, the project is to create an automated pizza order system in PHP and MySQL on Apache. The system works through the following steps:
- Customer places order -> Baker receives order, proceeds -> Driver receives order at certain state, proceeds
- Customer can view order at all time through session
Now I hung up at the last step: The driver can see a page that has a table with the information that the baker worked with and passed on (all changes are on database side). The driver can only see a whole package (whenever all pizzas are marked as a certain status, also saved in DB).
For this, I have the following SQL statement
SELECT PizzaID, BestellungID, Adresse, PizzaName, Preis, Status FROM angebot, bestelltepizza, bestellung where bestellung.bestellungid = bestelltepizza.fbestellungid and angebot.PizzaName = bestelltepizza.fPizzaName and (select min(status) from bestelltepizza where bestellung.bestellungid = fbestellungid) >2 ORDER BY Status, BestellungID
Now, when I use var_dump() to get the mysqli_num_rows() output, I get no errors and the following output int 26. Compared to the database rows, it's the correct number. I fetch the sql:
while($row = mysqli_fetch_array($this->result)) {
var_dump(mysqli_num_rows($this->result));
var_dump($row);
...
}
Within the while() loop contains another query
$this->query = "SELECT fPizzaName FROM bestelltepizza WHERE fBestellungID = '$BestellID'";
var_dump($this->query);
$tmpResult = $this->_database->query($this->query);
$count = mysqli_num_rows($tmpResult);
Now here is the problem, the while() loop leaves out a random $BestellID which can contain x rows of data. But when I count the output of var_dump() everything is correct. However, var_dump($this->query); is not showing the query statement for the specific jump, too.
Any ideas what this could be? Full link to pastebin below.
To not extend this question to the fullest, I uploaded the whole code to pastebin here: http://pastebin.com/u888CPLw
Offtopic: Appreciate any help, thanks. If I failed clearing out my exact problem or if any questions pop up to my question, please comment and I will clarify. Thanks.
while($row = mysqli_fetch_array($this->result)) {
$count = mysqli_num_rows($tmpResult);
for($i = 0; $i < $count; $i++) {
$tmpVar = mysqli_fetch_array($this->result);
Ive snipped the code to show the problem
$count is based on $tmpResult you are then doing a fetch array on $this->result you should be doing it on $tmpResult
As Marc B says, Its a simple query to either inner join / left join on to the query. It would be better to use the join.

PHP & SQL: update record issue

Having some difficulty pinpointing exactly what is wrong with this block of code. I am expecting it to run through a loop a set number of times and update some rows in the table tbl_games with some values received from the form.
I have tried running the code in phpMyAdmin without variables, which works fine (updates specified row). I assume the problem is something to do with the string in $insert_q.
gamecount will always be an int<30, game_ID will be a unique primary key integer value in tbl_games.
A little background: this code is part of a bigger project - which is centered around football games. An admin adds games to tbl_games (coded and finished), this current file now displays games to the admin which are unplayed (scores for team1 and team2 are NULL) and gives them a space to input scores for each team. This code takes those 2 scores, and the game_ID and updates each row.
It's having no effect on the DB rows though. Please point me in the right direction.
<?php
$lim=$_SESSION['gamecount'];
for ($i=1; $i<$lim; $i++) {
$game_ID = ${"_SESSION['game".$i."_ID']"};
$score_team_1 = ${"_REQUEST['".$i."_team1-score']"};
$score_team_2 = ${"_REQUEST['game".$i."_team2-score']"};
$insert_q = "UPDATE tbl_games SET team1_score = '$score_team_1', team2_score = '$score_team_2' WHERE game_ID = '$game_ID';";
mysql_query($insert_q);
}
session_destroy();
?>
I think the problem is with this line.
$game_ID = ${"POST['game".$i."_ID']"};
It should be something like this.
$game_ID = ${"_POST['game".$i."_ID']"}; or
$game_ID = $_POST['game'.$i.'_ID']; //much cleaner
You need to make use of the mysql reporting. Get it to output any errors, and affected rows. While you may think affected rows will be none, it might not be (always good to check when debugging just so you check everything).
Does your PHP error log have any warnings or other notices that might point to your query being an issue etc?
What is the value you're updating (echo out the var/session) and what is the DB value (look at it in phpmyadmin or mysql command line).
Could be there's nothing to update.

joomla-php mysql not updating a record with data from previous query

I'm counting the right answers field of a table and saving that calculated value on another table. For this I'm using two queryes, first one is the count query, i retrieve the value using loadResult(). After that i'm updating another table with this value and the date/time. The problem is that in some cases the calculated value is not being saved, only the date/time.
queries look something like this:
$sql = 'SELECT count(answer)
FROM #_questionsTable
WHERE
answer = 1
AND
testId = '.$examId;
$db->setQuery($sql);
$rightAnsCount = $db->loadResult();
$sql = 'UPDATE #__testsTable
SET finish = "'.date('Y-m-d H:i:s').'", rightAns='.$rightAnsCount.'
WHERE testId = '.$examId;
$db->setQuery($sql);
$db->Query();
answer = 1 means that the question was answered ok.
I think that when the 2nd query is executed the first one has not finished yet, but everywhere i read says that it waits that the first query is finished to go to the 2nd, and i don't know how to make the 2nd query wait for the 1st one to end.
Any help will be appreciated. Thanks!
a PHP MySQL query is synchronous ie. it completes before returning - Joomla!'s database class doesn't implement any sort of asynchronous or call-back functionality.
While you are missing a ';' that wouldn't account for it working some of the time.
How is the rightAns column defined - eg. what happens when your $rightAnsCount is 0
Turn on Joomla!'s debug mode and check the SQL that's generated in out the profile section, it looks something like this
eg.
Profile Information
Application afterLoad: 0.002 seconds, 1.20 MB
Application afterInitialise: 0.078 seconds, 6.59 MB
Application afterRoute: 0.079 seconds, 6.70 MB
Application afterDispatch: 0.213 seconds, 7.87 MB
Application afterRender: 0.220 seconds, 8.07 MB
Memory Usage
8511696
8 queries logged.
SELECT *
FROM jos_session
WHERE session_id = '5cs53hoh2hqi9ccq69brditmm7'
DELETE
FROM jos_session
WHERE ( TIME < '1332089642' )
etc...
you may need to add a semicolon to the end of your sql queries
...testId = '.$examID.';';
ah, something cppl mentioned is the key I think. You may need to account for null values from your first query.
Changing this line:
$rightAnsCount = $db->loadResult();
To this might make the difference:
$rightAnsCount = ($db->loadResult()) ? $db->loadResult() : 0;
Basically setting to 0 if there is no result.
I am pretty sure you can do this in one query instead:
$sql = 'UPDATE #__testsTable
SET finish = NOW()
, rightAns = (
SELECT count(answer)
FROM #_questionsTable
WHERE
answer = 1
AND
testId = '.$examId.'
)
WHERE testId = '.$examId;
$db->setQuery($sql);
$db->Query();
You can also update all values in all rows in your table this way by slightly modifying your query, so you can do all rows in one go. Let me know if this is what you are trying to achieve and I will rewrite the example.

Categories