Reputation: 1105
I am building an dynamic SQL Query. I have four input values which is passing from Android to PHP MySQL. The user may enter all values or leave some values empty. I want build an SQL query if the input of the any variable present. The complete SQL Query looks like
SELECT * FROM Movies WHERE `imdb_rat` IN ($val1) OR `Rotten_rate` IN ('$val2') OR $stringgen OR `Year` IN ('$val4')
The four inputs are $val1, $val2, $stringgen & $val4.
I've tried the below steps but it's not working:
$QueryString="SELECT * FROM Moviess WHERE 1=1";
if (!empty($val1)) {
$QueryString=$QueryString+" imdb_rat` IN ($val1)";
}
if (!empty($val2)) {
$QueryString=$QueryString+" `Rotten_rate` IN ($val2)";
}
if (!empty($val4)) {
$QueryString=$QueryString+" OR `Year` IN ($val4)";
}
echo $QueryString;
$result = mysql_query($QueryString);
How to build SQL query when if any input is present otherwise ignore the variable in the query?
Upvotes: 0
Views: 54
Reputation:
if (isset($val4) && !empty($val4)) {
$QueryString.=$QueryString+" OR `Year` IN ($val4)";
}
Upvotes: 1
Reputation: 7661
Try:
$QueryString="SELECT * FROM Moviess WHERE 1=1";
if (!empty($val1)) {
$QueryString .= " imdb_rat` IN ($val1)";
}
if (!empty($val2)) {
$QueryString .= " `Rotten_rate` IN ($val2)";
}
if (!empty($val4)) {
$QueryString .= " OR `Year` IN ($val4)";
}
echo $QueryString;
$result = mysql_query($QueryString);
.=
is used to concatonate to the first variable mention. The use of +
in a string is used in JavaScript. +
in PHP would mean 1 + 1 = 2
which isn't what you want for a string.
Also note that mysql_*
is deprecated and is removed in PHP7 instead use mysqli_*
or PDO
Upvotes: 1