【问题标题】:Function arguments php not working函数参数php不起作用
【发布时间】:2014-12-14 22:49:42
【问题描述】:

所以,我正在尝试通过在 url 中使用 category_id 的函数来获取论坛标题的名称。

它没有返回标题。是的,我包括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);

另外,我知道正在设置变量,只是没有通过函数。

【问题讨论】:

  • 您的变量echo $forumsCategories3; 没有值。您在那里填充了其他几个变量,但不是那个。
  • 总是在开发代码的时候,开启PHP的错误显示。它会抱怨未定义的变量$forumsCategories3。在你的脚本顶部:error_reporting(E_ALL); ini_set('display_errors', 1);
  • @Ghost 在下面指出了这一点——通过将$cid 直接传递到 SQL 字符串中,您将获得 none 的 PDO 安全优势。现在是学习正确使用 prepare()/execute() 绑定参数的时候了。

标签: php html mysql pdo


【解决方案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

}

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2011-06-02
    • 2011-04-24
    相关资源
    最近更新 更多