Reputation: 89
I'm having trouble with my MySQL results, I have a table named "posts" and one column is named "category" which is an integer value. I created a variable to get the category number from the browser depending on which category link a user clicks on.
If the category number is "1" it should display a test post(which is does). But if the category number is anything other than "1" which is the category id, it still shows the same test post when it should say "No results found" since it is querying for a different category id number.
I'm guessing it has something to do with the SQL syntax cause I've done added single-quotes around the variable name, and it error'd out so I removed them. I'm only posting the necessary code below cause I know it has something to do with that variable in the SQL:
// Variable to hold number
$category = is_numeric($_GET["c"]);
// Query
$query = "SELECT * FROM posts WHERE category = $category";
NOTE: Now i'm having a different issue. I need to make it so when there are results the while statement goes through and displays them, but if there are no results, display another message. The issue is it wont display the no results message when there are no results. Here is my code:
while($results = mysqli_fetch_assoc($query))
{
echo '$results["title"] <br>';
}
if(count($results) == 0 || count($results) == null) {echo 'No results';}
I've tried placing the if statement in the while and outside like so, but neither way works. I have to have the while statement cause I know i'll have more than one result so I can't use an if statement. The while statement needs an else!
Upvotes: 2
Views: 57
Reputation: 3832
is_numeric
returns true/false, so your query is "SELECT * FROM posts WHERE category = true"
Try this:
if(is_numeric($_GET["c"])) {
$category = $_GET["c"];
} else {
// exit the script or set a default value
}
// ...
Upvotes: 1
Reputation: 2670
cast it to int!
$category = (int) $_GET["c"];
and then
if (!empty($category))
{
// do your stuffff
}
Upvotes: -1
Reputation: 6687
You're turning the category into a boolean value.
You actually want this:
$category = intval($_GET['c']);
Upvotes: 3