0

I have a blog where I'm selecting the articles from a database using PHP. The problem is that becuase of my search terms I'm hitting an error. Here is my code:

<?php
if(isset($_GET["cat"])){
   $cat = $_GET["cat"];
}else{
    $cat = "all";
};
?>
<?php
if($cat == "all"){
    $cat_var = "";
}else{
    $cat_var = "WHERE cat = '$cat'";
}; // NOTE THIS LINE
?>
<?php
if(isset($_GET["issue"])){$issue = $_GET["issue"];}else{
    $issue = "all";
};
?>
<?php
if($issue == "all"){
    $issue_var = "";
    $limit = 4;
}
else{
    $issue_var = "AND issue = '$issue'"; // NOTE THIS LINE
    $limit = 200;
};
?>
<?php
$count_posts_sql = "SELECT id FROM articles $cat_var $issue_var"; // NOTE THIS LINE
$count_posts_res = mysqli_query($con, $count_posts_sql);
$num_init_posts = mysqli_num_rows($count_posts_res);
//If None, Then Exit
if($num_init_posts == 0){
    header("Location: /home");
    exit();
}
...
?>

So my url would be http://website.com/articles/all/2015-10, which is what I want. However $cat_var & $issue_var is causing the error because it's selecting:

SELECT * FROM articles AND issue = '2015-10' // NO WHERE STATEMEMT IS SHOWN

How do I overcome this error?

4
  • 1
    Put your criteria into an array. When you're generating your SQL, check to see if that array has contents, and if it does, cat WHERE and implode your array onto it. Commented Oct 24, 2015 at 15:00
  • Sounds complicated for a beginner. Just thinking, isn't there a way of doing something like WHERE cat = ANYTHING? Commented Oct 24, 2015 at 15:01
  • Add a print_r($_GET); to the top of the script, and show what you get from that in your question Commented Oct 24, 2015 at 15:03
  • 1
    You could always do WHERE cat LIKE '%', which will match anything, but there may be performance issues. Commented Oct 24, 2015 at 15:03

2 Answers 2

1

You could get this going by sticking a WHERE 1=1 in

$count_posts_sql = "SELECT id FROM articles WHERE 1=1 $cat_var $issue_var"; // NOTE THIS LINE

This is because you start off with an AND value = 1 without starting the WHERE clause, which creates an invalid query.

Then take the WHERE out of this line and replacing it with an AND:

$cat_var = "AND cat = '$cat'";
Sign up to request clarification or add additional context in comments.

Comments

1

You can initialize your where query string like this:

$where = 'WHERE 1 = 1 ';

and for there after you can concatenate depending on your inputs.

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.