2013-02-12 97 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不變。數組的鍵總是字符串。希望有所幫助。