2

假设我有一个包含 4 个字段的 mySQL 数据库表:

  • link_id(主键)
  • page_id
  • 锚文本
  • 网址

我的数据如下所示:

link_id | page_id | anchor_text | url 
1       | 1       | Link One    | http://www.one.com
2       | 1       | Link Two    | http://www.two.com
3       | 2       | Link Three  | http://www.three.com

我如何最好地编写一个函数来获取给定页面的链接,然后使用该函数来显示它们?

功能:

    function get_page_links($page_id) {

        $db = new mysqli("localhost", "root", "root", "my_db");

        //what's next?

        }

用法:

$my_links = get_page_links(1);

//do something to parse $my_links

展示:

<a href="http://www.one.com">Link One</a>
<a href="http://www.two.com">Link Two</a>
4

2 回答 2

2
$q = "SELECT *";
$q.= " FROM yourtablename";
$q.= " WHERE `page-id` = ".(int)$page_id;
$q.= " ORDER BY `link-id`";

可能不需要反引号,但我将它们扔在那里,因为您的字段名称中有连字符。

请注意,这里正在进行非常基本的验证。通过$page_id在附加之前强制转换为 int,您可以确保它不会是某种注入攻击。这不是一个很好的方法,但它会起作用。

类似的东西mysqli_real_escape_string()是应该考虑的替代方案,尤其是对于更一般的消毒。

或者:

$q = sprintf("SELECT *
              FROM yourtablename
              WHERE `page-id` = %d
              ORDER BY `link-id", $page_id);

我更喜欢哪个。


编辑回复:现在呢?

首先,让我们不要使用 mysqli,让我们使用PDO

其次,我们不想在每次调用函数时都连接到数据库,我们只想这样做一次。所以把它移出函数。

// Typically this line is in another file and included once, but for now lets just
//  get this out of the function
$db = new PDO('mysql:host=localhost;dbname=my_db', 'root', 'root');

// Your function
function get_page_links($page_id) {
    // Build query
    $q = sprintf("SELECT *
                  FROM yourtablename
                  WHERE `page-id` = %d
                  ORDER BY `link-id`", $page_id);
    // Run Query
    foreach ($db->query($q) as $a) {
        printf('<a href="%s">%s</a>'."\n", $a['url'], $a['anchor-text']);
    }
}
于 2012-06-16T17:38:42.460 回答
2

对我来说似乎是一个相当简单的查询

SELECT *
    FROM `links_table`
    WHERE `page_id` = $page_id
    ORDER BY `link_id` ASC;

这当然是假设$page_id不是来自用户输入,并且是经过安全清理的。如果没有,您应该使用准备好的语句。

阅读有关在 MySQLi 上执行语句以了解如何处理此查询生成的结果。


我不精通 MySQLi,因为我更喜欢 PDO。在 PDO 中,我会这样做:

<?php

/**
 * @param integer $page_id
 * @param PDO     $db
 *
 * @return array
 */
/*
 * First, we give the function the database connection object as an argument.
 * A function to get the page links shouldn't care where you got the connection from!
 */
function get_page_links($page_id, PDO $db) {
    $query = <<<MySQL
SELECT *
    FROM `links_table`
    WHERE `page_id` = :page_id
    ORDER BY `link_id` ASC;
MySQL;
    /*
     * Prepare the query and bind all values to placeholders
     */
    $stmt  = $db->prepare($query);
    $stmt->bindValue(":page_id", $page_id, PDO::PARAM_INT);

    $stmt->execute();

    /*
     * Fetch all results to an array, and return it
     */
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}

try {
    /*
     * Start new PDO connection for the function
     */
    $db = new PDO("mysql:host=localhost;dbname=database_name", "user", "password");
    //This line tells PDO to throw PDOExceptions in case of errors,
    //which are much easier to handle
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //This lines disables PDO's default emulation for prepared statements. Adds security.
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $links = get_page_links(1, $db);
}
catch (PDOException $e) {
    die("There has been an error with the database: " . $e->getMessage());
}

foreach ($links as $link) {
    echo "<a href='{$link["url"]}'>{$link["anchor_text"]}</a>";
}
于 2012-06-16T17:39:41.570 回答