Jump to content

dealing with VARIABLES in WHERE statements or in mysql queries in GENERAL.....


dsaba

Recommended Posts

hello everyone I have a problem where I can't figure out what to do in a particular coding situation

let me explain:

 

I am making a mysql query with a variable for the WHERE clause

like this:

 

$samplequery = mysql_query("SELECT filename FROM mainfilelist WHERE $whereclause ORDER BY dateadded");

 

$whereclause would normally equal something like this:

$whereclause = "'filelanguage'='English'";

 

the problem is I also want to generate this mysql query where there is NO WHERE CLAUSE

so if I leave $whereclause blank:

$whereclause = "";

 

you can see where this is a problem in the generated mysql query:

$samplequery = mysql_query("SELECT filename FROM mainfilelist WHERE  ORDER BY dateadded");

 

there are TWO spaces in between WHERE and ORDER BY and that is an error in mysql syntax

also the WHERE is still part of the query although there is no whereclause needed

 

 

How do I fix this problem?

-thanks


<?php
$whereclause = "'filelanguage'='English'"; // or ""
if(empty($whereclause))
{
$samplequery = mysql_query("SELECT filename FROM mainfilelist ORDER BY dateadded");
}else{
$samplequery = mysql_query("SELECT filename FROM mainfilelist WHERE $whereclause ORDER BY dateadded");
}

?>

 

or

 

<?php
$whereclause = "'filelanguage'='English'"; // or ""
if(!empty($whereclause))
{
$whereclause = " WHERE ".$whereclause;
}
$samplequery = mysql_query("SELECT filename FROM mainfilelist $whereclause ORDER BY dateadded");
?>

 

or

 

<?php
$whereclause = "'filelanguage'='English'"; // or ""
if(!empty($whereclause))
{
$whereclause = " WHERE ".$whereclause;
}
$samplequery = mysql_query("SELECT filename FROM mainfilelist $whereclause ORDER BY dateadded");
?>

 

thanks for the help mad, I will use the first one, the second is not correct, because if the whereclause is NOT emtpy you will be missing a "WHERE" in the query

Yeah, it was hard for me at first.  The obvious advantage is that you from 6 lines of code down to 2.  It also saves on file size.  However, these are both "minute" but if you are anal like I have been told I am, I will nickel and dime anything.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.