2

So I am trying to involve an if statement in my SQL query in my PHP code. Basically, I want to say "if $var is not 0, add the WHERE clause, but if $var is 0, don't add it".

Code below, doesn't seem to be working. Help is greatly appreciated!

$var = $_GET["var"];

$query = sprintf("SELECT * FROM table ".if($var != 0) { echo "WHERE var = '%s'," }."
  if($var != 0) { mysql_real_escape_string($var) });

$result = mysql_query($query);

Update

I ultimately decided that since I will be using multiple conditions for multiple variables, it was best to do the following:

$var = $_GET["var"];
$string ='';
if ($var != 0) {
  $string = "WHERE var =". $var . " ";
}

$query = sprintf("SELECT * FROM table ". $string.");

$result = mysql_query($query);

Now I can use as many variables as I want and add additional clauses to the SQL statement.

Thanks for the help!!

4 Answers 4

4

You can't have an if expression inside string concatentation. Also, you're missing the trailing ".

$query = sprintf("SELECT * FROM table ". $var != 0 ? "WHERE var = '%s'" : "");

Also, mysql_real_escape_string() doesn't take the variable by reference, so the modified string is returned:

if($var != 0) { $var = mysql_real_escape_string($var) });
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

$query = sprintf("SELECT * FROM table%s", $var != 0 ? " WHERE var = '" . mysql_real_escape_string($var) . "'" : "");

Comments

2

Don't use PHP for this; use the database.

$db = new PDO($dsn, $username, $password, $database);
$stmt = $db->prepare('SELECT * FROM table WHERE (:select <> 0 AND column = :value)');
$stmt->execute(array(':select' => $var, ':value' => $var));

2 Comments

It's a completely MySQL way. Would you please comment an example result that it might produce? I want to learn this query. Thank you
That depends on the data you have: that query tells the database to only collect rows where both column is exactly equal to $value and a user specified parameter is not equal to zero. The point is that database is more than just a giant hash table for storing data; they're also capable of filtering and operating on massive amounts of data very efficiently -- much more so than PHP is.
0
$var = $_GET["var"];
$string ='';
if ($var != 0) {
  $string = "WHERE var =". $var . " ";
}

$query = sprintf("SELECT * FROM table ". $string.");

$result = mysql_query($query);

Comments

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.