2014-10-20 91 views
1

所以,我試圖通過在URL中使用category_id通過函數獲得論壇標題的名稱。函數參數PHP不工作

它沒有返回標題。是的,我包括functions.php

的鏈接是:

http://www.dxbridge.com/view_category.php?cid=1 

的functions.php:

function getForumsCategoriesName($cid) { 

    $query = "SELECT * FROM categories WHERE id='" . $cid . "'"; 

    try { 
     global $db; 
     // Execute the query against the database 
     $stmt = $db->prepare($query); 
     $stmt->execute(); 
     $result = $stmt->fetchAll(); 
     foreach($result as $forums) { 
      $forumsID = $forums['id']; 
      $forumsTitle = $forums['category_title']; 
      $forumsTopicAmount = $forums['topic_amount']; 
      $forumsCategoriesName = "<h1>" . $forumsTitle . "</h1>"; 
      echo $forumsCategories3; 
     } 
    } 
    catch(PDOException $ex) { 
     // Note: On a production website, you should not output $ex->getMessage(). 
     // It may provide an attacker with helpful information about your code. 
     die("Error loading names"); 
    } 
} 

試圖從功能

$cid = $_GET['cid']; 
getForumsCategoriesName($cid); 

還搶了名字,就知道該變量被設置,它只是沒有通過函數。

+0

你的變量'$回聲forumsCategories3;'不具有價值。你還有其他幾個變量,但沒有。 – 2014-10-20 01:50:56

+0

總是在開發代碼時,打開PHP的錯誤顯示。它會抱怨一個未定義的變量'$ forumsCategories3'。在腳本的頂部:'error_reporting(E_ALL); ini_set('display_errors',1);' – 2014-10-20 01:51:41

+2

@Ghost指出以下內容 - 通過將'$ cid'傳遞給您的SQL字符串,您將獲得PDO的安全優勢。現在是學習使用bounding參數正確使用'prepare()/ execute()'的時候了。 – 2014-10-20 01:52:47

回答

1

你還沒有返回/回顯任何東西(實際上你迴應了一些未定義的變量)。綁定值,不要直接注入它的查詢字符串:

function getForumsCategoriesName($cid) 
{ 
    $result = array(); 
    try { 
     global $db; 

     // Execute the query against the database 
     $query = 'SELECT * FROM categories WHERE id = :cid '; // put a named placeholder 
     $stmt = $db->prepare($query); 
     $stmt->bindParam(':cid', $cid); // bind the value 
     $stmt->execute(); 
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
     return $result; // return the values 
     // echo $forumsCategories3; // this doesn't make sense, its undefined. 
    } 
    catch(PDOException $ex) { 
     // Note: On a production website, you should not output $ex->getMessage(). 
     // It may provide an attacker with helpful information about your code. 
     die("Error loading names"); 
    } 
} 

然後在用法:

$cid = $_GET['cid']; 
$result = getForumsCategoriesName($cid); 

foreach($result as $forums) { 
    $forumsID = $forums['id']; 
    $forumsTitle = $forums['category_title']; 
    $forumsTopicAmount = $forums['topic_amount']; 
    $forumsCategoriesName = "<h1>" . $forumsTitle . "</h1>"; 

    echo $forumsID . '<br/>'; // echo everybody else 

}