php - Dynamic select query according to form fields
I have a form with two fields. The user can fill in either one or both and the MySQL database should be queried accordingly.
Here is my php code:
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}
$data = mysql_query($query) or die("Couldn't execute query. ". mysql_error());
The code works fine if either number1 or both of the fields are filled in. However when only the second field is filled in I get the error:
Couldn't execute query. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
If I echo the query it is shown correctly:
SELECT * FROM table WHERE number2 = entered value
Any help is much appreciated! Thanks!!
Answer
Solution:
have you forget escape values? u can use somthing like this
mysql extension is deprecated, use mysqli instead
Answer
Solution:
try this
Answer
Solution:
I think you get the error because of the assignment. You wrote $set===TRUE, its == not === The error is here: