I have been using the same code for years and all of a sudden I’m having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.
2
Answers
your query states
SELECT * FROM database WHERE name='".$name."'
, this means that your table name isdatabase
, now i dont know how you actually created this table butdatabase is a MYSQL reserved keyword
change the name of your table to something else or just change your query toassuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
this is more secure
You shouldn’t use mysqli excepted for old projects you can’t upgrade, it’s outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
Here’s the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.