0

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?

6
  • 1
    if (!empty($val4) && isset($val4)) { $QueryString=$QueryString+" OR Year IN ($val4)"; } Commented Dec 29, 2015 at 12:47
  • 1
    @Niyaz empty() does the same as isset() but also checks if the variable isn't empty so (!empty($val4) && isset($val4)) is like writing double code Commented Dec 29, 2015 at 14:25
  • empty checks undefined ? Commented Dec 29, 2015 at 14:27
  • @Niyaz well if it hasn't been set it's also empty Commented Dec 29, 2015 at 14:32
  • Thanks for you answer bro , got it . Commented Dec 29, 2015 at 14:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
if (isset($val4) && !empty($val4)) { 
      $QueryString.=$QueryString+" OR `Year` IN ($val4)"; 
} 

1 Comment

Hi Niyaz, it is useful to everyone if you could edit your answer to explain the why this should be used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.