2013-02-12 96 views
0

我得到这个代码用于获取类别名称,并显示该类别中的项目:

<?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> 

它给了我这个错误:

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

我需要的仅仅是从$cat变量(如show.php?cat=6)中的类别中显示cat_name

+0

您需要'$ _GET ['cat']'不要发帖,最好只在以下情况下调用您的数据库:a)您创建(转义)您的$ cat变量,b)$ cat不为空() – Najzero 2013-02-12 08:11:22

+0

变量like show .php?cat = 6是获取请求,尝试使用$ _GET数组 – BattleBit 2013-02-12 08:12:26

+0

使用$ _GET [“cat”]而不是$ _POST [“cat”]; – ripa 2013-02-12 08:13:58

回答

0

做这样的,

$cat = ""; 
if(isset($_GET['cat'])) { 
    $cat=$_GET['cat']; 
} 
+0

WORKS LIKE A CHARMףׁ – user2003332 2013-02-12 08:29:31

+0

现在我需要显示产品的图片,该图片以id号命名。没有这样工作:$ cat_list。=“产品ID:$ id - $ product_name -
”; – user2003332 2013-02-12 08:30:39

0
  1. 你没得到$猫值,将其更改为$_GET;

  2. 为了确保您的查询一样,在未来不破,广告'到IDS太:

SELECT 
    * 
FROM 
    products 
    ,prod_cat 
    ,categories 
WHERE 
    categories.id=prod_cat.cat_id 
    AND products.id=prod_cat.prod_id 
    AND categories.id='$cat'
0
show.php?cat=6 

在您的网址意味着你使用的是GET变量。使用

$_GET['cat'] 

此外:

  1. 请做点什么安全。人们可以将他们想要的任何东西放入该GET变量中,这样他们就可以将他们想要的东西添加到SQL中!这不好!
  2. 请阅读mysql*函数的PHP手册页上的通知:它们已被弃用,不应使用。使用PDO或MySQLi
1

$_GET$_POST是不一样的。在这种情况下,您正尝试访问show.php?cat=6,因此您应该使用$_GET['cat']

一般:

  • $ _GET从查询字符串,或您的网址检索变量。
  • $ _POST从POST方法(如窗体)中检索变量。

PHP.net手册:
$ _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.

1

首先使用$ _GET或$ _REQUST而不是$ _ POST 。并且确保你保护你的输入。试试这个功能:

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; 
} 

,并使用它像这样

$cat = protect($_REQUEST['cat']); 

最后,我认为这里存在这里的语法。 这里

$cat_list= "$results[cat_name]"; 

此行应该是

$cat_list= $results['cat_name']; 

它一直在寻找一个叫cat_name不变。数组的键总是字符串。希望有所帮助。