I have a question about the best way for writing a conditional query in PHP to produce correct MySQL syntax based on PHP variables.
Here's my PHP code showing the block where the 2 variables are evaluated...
Code: Select all
// SQL QUERY FOR PUBLICATIONS
$sql_query = "SELECT * FROM publications WHERE ";
// CHECK WEB VAR
if ( isset($_GET['nonweb'])) {
$sql_query .= "1";
} else {
// WEB FILTER NOT SET - SHOW ONLY WEB ONES
$sql_query .= "web=1";
}
// CHECK PUBLICATION VAR
if ( isset($_GET['filter'])) {
// PUBLICATION FILTER SET
$filter = mysql_real_escape_string($_GET['filter']);
$sql_query .= " AND publication LIKE \"%$filter%\"";
}
$sql_query .= " ORDER BY art_date ASC LIMIT 0, 10000";
$sql_result = mysql_query($sql_query);Code: Select all
SELECT * FROM publications WHERE 1 AND publication LIKE "%AMD%" ORDER BY art_date ASC LIMIT 0, 10000The query works.
But because of the way I've structured my PHP code around line 6 checking that first var, I could have ended up with the following query...
Code: Select all
SELECT * FROM publications WHERE AND publication LIKE "%AMD%" ORDER BY art_date ASC LIMIT 0, 10000So is it appropriate to just drop a 1 in there like I have to fill the gap in the query if certain conditions in my PHP are not met?
Hope this makes sense
Thanks
Ben