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(...).
Related
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
In my test-surroundings there is a database containing some Person Information (Name, E-Mail, Adress etc.). These Informations can be inserted by anyone into the database via a form. In the background they are inserted with a parameterized INSERT into the database after submission.
What I now would like to do is to detect if some person tries to insert the same values into the database again, and if he does, not inserting the new values and instead showing an error message. (So every person name in the database is unique, there are no multiple rows linked to one name).
I had a numerous number of ideas on how to accomplish this. My first one was to use a query like REPLACE or INSERT IGNORE, but this method would not give me feedback so I can display the error message.
My second attempt was to first do a SELECT-query, checking if the row already exists, and if num_rows is greater than 0, exit with the error message (and else do the INSERT-part). For this to work I will have to use parameterized queries for the SELECT too, as I´m putting some user input into it. Figuring that parameterized queries need special functions for everything you could normally do with way less lines of code, I researched in the internet on how to get num_rows from my $statement parameterized-statement-object. This is what I had in the end:
$connection = new mysqli('x', 'x', 'x', 'x');
if (mysqli_connect_error()) {
die("Connect Error");
}
$connection->set_charset("UTF-8");
$statement = $connection->stmt_init();
$statement = $connection->prepare('SELECT Name FROM test WHERE Name LIKE ?');
flags = "s";
$statement->bind_param($flags, $_POST["person_name"]);
$statement->execute();
$statement->store_result();
$result = $statement->get_result(); //Produces error
if ($result->num_rows >= 1) {
$output = "Your already registered";
} else {
$output = "Registering you...";
}
exit($output);
After all, I can´t get why mysqli still won´t give me num_rows from my statement. Any help is appreciated, thanks in advance!
Oh, and if you guys could explain to me what I have to do to get affected_rows,that would be awesome!
EDIT: I know I could to this by using unique constraints. I also found out that I can find out if INSERT IGNORE skipped the INSERT or not. But that won´t answer my complete question: Why does the SELECT num_rows alternative not work?
ANOTHER EDIT: I changed the code snippet to what I now have. Although my mysql(i)-version seems to be 5.6.33 (I echo´d it via $connection->server_info) get_result() produces the following error message:
Fatal error: Call to undefined method mysqli_stmt::get_result() in X on line X (line of get_result)
The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved. Note that if the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.
Also make sure that you declare ->store_result() first. Moreover the function doesn't work with LIMIT used jointly with SQL_CALC_FOUND_ROWS. If you want to obtain the total rows found you must do it manually.
EDIT:
If nothing from the suggestions does not work for you, then I would propose to rewrite your SQL query:
SELECT `Name`, (SELECT COUNT(*) FROM `Persons`) AS `num_rows` FROM `Persons` WHERE `Name` LIKE ?
This query will return the total number from your Persons table, as well as Name, if exist.
I am maintaining a server that runs for around 1 year. Nothings gonna be wrong previously. However, suddenly, there is an error in mysql_insert_id(), which returns 0, instead of normal row id from the database. Here's are the core of the code.
$sql = "INSERT INTO $db_table (name,email) VALUES('$name','$email')";
mysql_query($sql);
$current = mysql_insert_id();
Also notice that even if there are no changes in the code, the program runs smoothly again after the error has happened. It seems strange to me.
Here is my possible explanation. Since I am hosting in a public server, where many are using the same MYSQL server. Will it be that when mysql_query($sql), the server then swap the process and let another guy to run another SQL command, which may be for example, a SELECT statement, and after their execution, it swaps back to my own code and continue executing, which results in 0?
Please help. Thanks.
to be sure use the resource_identifier as parameter in mysql_queryand mysql_insert_id.
If you don't, the last connection to the mysql server is used, as you thought.
$resource = mysql_connect(...);
$sql = "INSERT INTO $db_table (name,email) VALUES('$name','$email')";
mysql_query($sql, $resource);
$current = mysql_insert_id($resource);
Please consider using mysqli oder PDO since mysql_* functions are deprecated and are going to be removed in future PHP-Versions
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.
We have a function used within our PHP/MySQL application which returns basic configuration information, it contains a simple select query and looks like this:
public function getConfigurationValue($field)
{
$res = mysql_query("SELECT `cfg_value` FROM `ls_config` WHERE `cfg_name` = '".mysql_real_escape_string($field)."'");
$cfg = htmlspecialchars(mysql_result($res,0));
return $cfg;
}
This problem we are having is that occasionally, seemingly at random, this query throws a mysql error on mysql_result saying that "supplied argument is not a valid mysql result resource". In our debugging we have determined though that this is not because $field is not being passed. Essentially, for a reason we cannot determine a perfectly valid query fails and returns no results causing an empty result set and the subsequent error. If the error was due to the mysql connection failing the script would have died well before this. Also, this function may be called 50-100 times on some page loads but it only tends to fail once on each load.
Please let me know if you need any other information to work this out.
Thanks.
searching for php "supplied argument is not a valid mysql result resource" reveals that to get the actual error, you'd need to call mysql_error, and the error that you get is because the result of the query is FALSE - this value not being a valid mysql result resource.
i.e. in short you have something like:
$res = FALSE; # should contain the mysql result but does not, due to error.
$cfg = htmlspecialchars(mysql_result($res,0)); # the attempt to call mysql_result on invalid argument errors out.
So you'd want to use something like this:
$query = "SELECT * FROM cats WHERE id=$id";
$qr1 = mysql_query ($query)
or die ("Query failed: " . mysql_error() . " Actual query: " . $query);
You might want to give this a shot and see what the underlying error message says.
Given that the error is "MySQL server has gone away", There can be multitude of reasons for it - this article would be a good start to investigate. Searching suggests also some php-related and stack-specific bugs, so it looks like you might need to debug it with a closer attention.
Maybe try to duplicate the setup on another box and then start experimenting with the versions/settings, and see if any of the already reported scenarios match your case. Unfortunately, seems there's no single simple answer to this.