Reputation: 5
I got this code for getting the category name and show the items in this category:
<?php
// This block grabs the whole list for viewing
$cat_list="";
$cat=$_POST['cat'];
$cat_sql="SELECT * FROM products,prod_cat,categories WHERE categories.id=prod_cat.cat_id AND products.id=prod_cat.prod_id AND categories.id=$cat";
$cat_query=mysql_query($cat_sql) or die(mysql_error());
$results=mysql_fetch_assoc($cat_query);
$cat_list= "$results[cat_name]";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>show</title>
</head>
<?php echo $cat_list; ?>
</html>
it gives me this error:
Notice: Undefined index: cat in show.php on line 12
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
All I need is to display the cat_name
out of the categories from the $cat
variable like show.php?cat=6
.
Upvotes: 0
Views: 118
Reputation: 810
First use $_GET or $_REQUST instead of $_POST. And also make sure you protect your input. Try this function:
function protect($string){
$string = urldecode($string); // url decode to make things like %20 into whitespace
$string = trim(strip_tags($string)); //remove whitespaces
$string = preg_replace("/'/", "", $string); //remove single quotes
return $string;
}
and use it like this
$cat = protect($_REQUEST['cat']);
Lastly, I think there is a syntax here here. This line here
$cat_list= "$results[cat_name]";
Should Be
$cat_list= $results['cat_name'];
It was looking for a constant called cat_name. The keys of arrays are always strings. Hope that helps.
Upvotes: 1
Reputation: 2043
$_GET
and $_POST
are not the same. In this case you are trying to access cat in show.php?cat=6
, so you should use $_GET['cat']
.
Generally:
PHP.net manual:
$_GET - http://php.net/manual/en/reserved.variables.get.php
An associative array of variables passed to the current script via the URL parameters.
$_POST - http://php.net/manual/en/reserved.variables.post.php
An associative array of variables passed to the current script via the HTTP POST method.
Upvotes: 1
Reputation: 64419
show.php?cat=6
in your url means you are using a GET
variable. use
$_GET['cat']
Furthermore:
mysql*
functions: they are deprecated and should not be used. Use PDO or MySQLiUpvotes: 0
Reputation: 8030
You did not get $cat value, change it to $_GET
;
To make sure, your query doesn't break like that in the future, ad '
to ids too:
SELECT * FROM products ,prod_cat ,categories WHERE categories.id=prod_cat.cat_id AND products.id=prod_cat.prod_id AND categories.id='$cat'
Upvotes: 0
Reputation: 5108
Do like this,
$cat = "";
if(isset($_GET['cat'])) {
$cat=$_GET['cat'];
}
Upvotes: 0