automatically executing mysql query from php not working - php

I'd like to automatically execute the following PHP script to autmoatically delete a row in table after 3 days. However, the script seems not working, even though the query already yield the correct result. I've tried to run it manually, and it also worked. I'm not sure whether I've written the script correctly, but here's the code:
<?php
require_once('../../resources/db_connect.php');
$query = "DELETE FROM user_orders WHERE date_order < DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND ID_status_order = 1";
$result = #mysql_query($query);
?>
I'm using xampp on Windows. I've tried to execute it via Windows Task Scheduler, but I don't think it's working. Any other idea?
Cheers

Hidding errors are not good enough. Thry and remove the # first and see what errors you are having. Come back and give the errors.

echo mysql_query($query) or mysql_error()

You aren't doing any error checking, and with the # in front of commands even actively suppressing errors. Use this to check for errors with your query or database connection:
mysql_query($query) or die(mysql_error());
If you want to check your query but don't want it to delete everything, add another condition to it:
... AND 1=0
which is always false, thus nothing gets deleted. MySQL will still check your query and give you errors, if e.g. some fields or the table are unknown.

Related

Unknown MySQL Insert Error

I'm trying to insert into my database and have been frustratingly not been able to get my statement(s) to work. I'm using PHP's MySQL Improved (mysqli) procedural interface. It might be worth noting that I'm using the c9.io IDE (pre-AWS) and everything including the server that my application is running on is through c9.
What I've noticed is that the statements have been working randomly. Initially, I was making very subtle changes to my INSERT statements until it worked, but after the working trial, it would fail again. So, eventually I started hitting the refresh button (same inputs, no modifications to my code) repeatedly until I hit a success.
In terms of code:
$sql = "INSERT INTO `users` (`email`,`password`) VALUES ('example#mail.com','1234')";
$result = mysqli_query($connection,$sql);
gives
$result = false
very consistently, but every random nth trial
$result = true
(same inputs, no change to my code).
I do not believe it is an error with my SQL syntax considering the random successes, nor do I believe it is an error with my connection. All of my SELECT statements have been working fine.
Thus, I have a hunch that for some reason it may be an issue with c9? If you have ever had a similar issue with any of MySQL, SQL, PHP, or c9, please help!
You Should try this
<?php
if (!mysqli_query($connection,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
{
echo("Error description: " . mysqli_error($connection));
}
?>
Use myqli_error() which will give you a error message which should help clarify the issue with your code

Why my database table is not getting updated

I used the correct command to update my database table
$result_col ="UPDATE `try`.`5` SET `D` = '$value' WHERE `5`.`A` = '$filenames[$index]' ;";
It works if i write in phpmyadmin to update the database table using the above command.
But it doesnot work in my code, though when i echo the command it prints correct values
UPDATE Store SET D='SUN: 2.495' WHERE `Index` = 'Hi35'
UPDATE Store SET D='SUN: 1.416' WHERE `Index` = 'He_41'
And it doesnot show any error or warnings , i also used this error_reporting(E_ALL)
What could be the possible reasons?
I checked Database link, It works
I checked the code, NO error reports or warnings
I pasted the command in phpamyadmin, the command works
I used mysqli instead of mysql, still the same problem
I did so many trials but still why the command doesnot work in the code?
Any idea??
it worked! there were spaces in the array $filenames, which was ignored in phpmyadmin, that is why the query worked in phpmyadmin and not in the php script...
Take the semicolon ';' out of your query string.

What am I doing wrong with inserting?

I tried both
$query = "INSERT INTO reservation VALUES ('".$hour."','".$minute."','".$day."','".$month."','".$year."','".$name."','".$table."')";
$query = "INSERT INTO reservation VALUES ('$hour','$minute','$day','$month','$year','$name','$table')";
But none of them work, I get a blank page, and no errors in my error logs. I tried doing echo to all the variables and I got their values.
Here is the overall function:
function makeReservation($trtime,$hour,$minute,$day,$month,$year,$name,$table,&$db)
{
//$query = "INSERT INTO reservation VALUES ('".$hour."','".$minute."','".$day."','".$month."','".$year."','".$name."','".$table."')";
$query = "INSERT INTO reservation VALUES ('$hour','$minute','$day','$month','$year','$name','$table')";
$result = $db->query($query) or die(mysql_error());
}
I'll make a few suggestions. First, I'll assume that you actually know what you're doing when you say there is no error.
1) Make sure you work on the good database. You can do a SHOW TABLES query to see what tables it contains, or a SELECT * FROM reservation to see its content.
2) Right after you insert the row, do a SELECT * FROM reservation query and check if your row is there.
3) Make sure you call your function...
Then, as I said in comments, you should use the DATETIME type instead of using different columns for hours, minutes, etc. If you need to select a particular attribute, use the appropriate function (for example, SELECT HOUR(your_column))
The quotes around integers shouldn't make your query fails, but it's still better for clean code purposes to remove them if not necessary (and make sure you escape your data correctly, of course).
The php you posted looks fine.
If you're getting a blank page, it's likely that something is failing before the function calls. Maybe a parsing error?
If you're not seeing anything in the error logs, try changing your error logging settings in the php.ini.
display_errors = E_ALL
If you're on shared hosting, you can often override using .htaccess http://davidwalsh.name/php-values-htaccess

Mysql Query inside a php variable

At my workplace, we were having problems with a certain field. From time to time we need to suspend someone from a mailing list, and to do that, we would just update their record to make the suspend field = Y.
That works no problem in phpMyAdmin, but when we use the crud pages for the staff, sometimes it fails to update, leaving the value of Suspend = N. After looking at the code, I wanted to know if the following line could be the source of the problem.
$rs = mysql_query($sql, $conn) or die("Query has Failed : $sql");
Everything else before it looks good, and it is the last line in the script. Now, I would think that this shouldn't work, but it does. This will run the query. I would think that it would only work if it was
mysql_query($sql, $conn) or die("Query has Failed : $sql");
But it seems to work fine on most occasions. Only every now and then it doesn't work. Could this be the cause of the problem? One last bit of information, we are using MyIsam for the engine.
I would appreciate any help you could give!
mysql_query will return a value whether you're assigning that return to a variable or not. By PHP's operator precedence rules, the first statement is seen as:
$rs = (
(mysql_query($sql, $conn))
or
(die("Query has Failed..."))
);
What's the query look like? Remember that mysql_query can return a "success" status, even though the query has failed to do what you intended. e.g. UPDATE ... SET ... WHERE (somefield = value_that_doesnt_exist);. The query didn't do what you wanted, but it also wasn't invalid, so mysql_query will not return FALSE and won't trigger the or die(...).

Why does this PHP code hang on calls to mysql_query()?

I'm having trouble with this PHP script where I get the error
Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/vhosts/richmondcondo411.com/httpdocs/places.php on line 77
The code hangs here:
function getLocationsFromTable($table){
$query = "SELECT * FROM `$table`";
if( ! $queryResult = mysql_query($query)) return null;
return mysql_fetch_array($queryResult, MYSQL_ASSOC);
}
and here (so far):
function hasCoordinates($houseNumber, $streetName){
$query = "SELECT lat,lng FROM geocache WHERE House = '$houseNumber' AND StreetName = '$streetName'";
$row = mysql_fetch_array(mysql_query($query), MYSQL_ASSOC);
return ($row) ? true : false;
}
both on the line with the mysql_query() call.
I know I use different styles for each code snippet, it's because I've been playing with the first one trying to isolate the issue.
The $table in the first example is 'school' which is a table which definitely exists.
I just don't know why it sits there and waits to time out instead of throwing an error back at me.
The mysql queries from the rest of the site are working properly. I tried making sure I was connected like this
//connection was opened like this:
//$GLOBALS['dbh']=mysql_connect ($db_host, $db_user, $db_pswd) or die ('I cannot connect to the database because: ' . mysql_error());
if( ! $GLOBALS['dbh']) return null;
and it made it past that fine. Any ideas?
Update
It's not the size of the tables. I tried getting only five records and it still timed out. Also, with this line:
$query = "SELECT lat,lng FROM geocache WHERE House = '$houseNumber' AND StreetName = '$streetName'";
it is only looking for one specific record and this is where it's hanging now.
It sounds like MySQL is busy transmitting valid data back to PHP, but there's so much of it that there isn't time to finish the process before Apache shuts down the PHP process for exceeding its maximum execution time.
Is it really necessary to select everything from that table? How much data is it? Are there BLOB or TEXT columns that would account for particular lag?
Analyzing what's being selected and what you really need would be a good place to start.
Time spent waiting for mysql queries to return data does not count towards the execution time. See here.
The problem is most likely somewhere else in the code - the functions that you are blaming are possibly called in an infinite loop. Try commenting out the mysql code to see if I'm right.
Does your code timeout trying to connect or does it connect and hang on the query?
If your code actually gets past the mysql_query call (even if it has to wait a long time to timeout) then you can use the mysql_error function to determine what happened:
mysql_query("SELECT * FROM table");
echo mysql_errno($GLOBALS['dbh']) . ": " . mysql_error($GLOBALS['dbh']) . "\n";
Then, you can use the error number to determine the detailed reason for the error: MySQL error codes
If your code is hanging on the query, you might try describing and running the query in a mysql command line client to see if it's a data size issue. You can also increase the maximum execution time to allow the query to complete and see what's happening:
ini_set('max_execution_time', 300); // Allow 5 minutes for execution
I don't know about the size of your table, but try using LIMIT 10 and see if still hangs.
It might be that your table is just to big to fetch it in one query.
Unless the parameters $houseNumber and $streetName for hasCoordinates() are already sanitized for the MySQL query (very unlikely) you need to treat them with mysql_real_escape_string() to prevent (intentional or unintentional) sql injections. For mysql_real_escape_string() to work properly (e.g. if you have changed the charset via mysql_set_charset) you should also pass the MySQL connection resource to the function.
Is the error reporting set to E_ALL and do you look at the error.log of the webserver (or have set display_erorrs=On)?
Try this
function hasCoordinates($houseNumber, $streetName) {
$houseNumber = mysql_real_escape_string($houseNumber);
$streetName = mysql_real_escape_string($streetName);
$query = "
EXPLAIN SELECT
lat,lng
FROM
geocache
WHERE
House='$houseNumber'
AND StreetName='$streetName'
";
$result = mysql_query($query) or die(mysql_error());
while ( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo htmlspecialchars(join(' | ', $row)), "<br />\n";
}
die;
}
and refer to http://dev.mysql.com/doc/refman/5.0/en/using-explain.html to interpret the output.
-If you upped the execution time to 300 and it still went through that 300 seconds, I think that by definition you've got something like an infinite loop going.
-My first suspect would be your php code since mysql is used to dealing with large sets of data, so definitely make sure that you're actually reaching the mysql query in question (die right before it with an error message or something).
-If that works, then try actually running that query with known data on your database via some database gui or via the command line access to the database if you have that, or replacing the code with known good numbers if you don't.
-If the query works on it's own, then I would check for accidental sql injection coming from with the $houseNumber or $streetName variables, as VolkerK mentioned.

Categories