0

I have been trying to find a solution to MySQLi stmt not having a fetch array function and I came upon this interesting bit of code. Do you think this code is worth using, no huge security flaws?

/*
 * Utility function to automatically bind columns from selects in prepared statements to
 * an array
 */
function bind_result_array($stmt)
{
    $meta = $stmt->result_metadata();
    $result = array();
    while ($field = $meta->fetch_field())
    {
        $result[$field->name] = NULL;
        $params[] = &$result[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), $params);
    return $result;
}

/**
 * Returns a copy of an array of references
 */
function getCopy($row)
{
    return array_map(create_function('$a', 'return $a;'), $row);
}

credit: http://gunjanpatidar.wordpress.com/2010/10/03/bind_result-to-array-with-mysqli-prepared-statements/

Requested by common sense:

 $db = new PDO("mysql:host='localhost';dbname='testing'", 'username', 'password') or die('Could not connect to server');
$get_posts = mysqli_stmt_init($db);
mysqli_stmt_prepare($get_posts, 'select * from Chatposts where Chatid = ? and CPid > ? and Deleted = ? order by CPid desc limit ?');
mysqli_stmt_bind_param($get_posts, 'iiii', $chatroomid, $lastpost, $deleted, $limit);
mysqli_stmt_execute($get_posts);
mysqli_stmt_bind_result($get_posts, $newcolumn['ID'], $newcolumn['Chatid'], $newcolumn['Name'], $newcolumn['URL'], $newcolumn['Text'], $newcolumn['Datetime'], $newcolumn['IPaddress'], $newcolumn['Deleted']);
mysqli_stmt_store_result($get_posts);
mysqli_stmt_fetch($get_posts); // Trying to fetch array
mysqli_stmt_close($get_posts);
4

1 回答 1

2

尽管我在这段代码中没有看到“巨大的安全漏洞”,但我认为无论如何都不值得使用。看,mysqli 让你无处可去。旧的 mysql 没有这样的问题,PDO 没有这样的问题。只有 mysqli 无缘无故地让你的生活变得复杂。

有时你可以通过使用来解决这个问题get_result(),但它不能保证工作,甚至不绑定到 PHP 版本 - 所以,你甚至不能事先告诉它。

更不用说尝试将任意数量的占位符绑定到查询时会遇到同样的问题,甚至没有半可行的解决方案!

所以,再一次 - 与其解决所有这些问题 - 为什么不使用像 PDO 这样的合理驱动程序呢?
使用 PDO,您可以直接使用熟悉的 fetch(),而无需像上面的代码这样的拐杖。

另一种解决方案是避免使用本机准备好的语句,并使用它们手动解析的等效语句,使用mysqli_query()它在任何方面都类似于旧的好 mysql_query。
但是这种方法对于普通用户来说似乎太复杂了——所以,使用PDO再好不过了。

这是您使用 PDO 的代码

$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => FALSE,
);
$pdo = new PDO($dsn,'root','', $opt);

$stm = $pdo->prepare('select * from Chatposts where Chatid = ? and CPid > ? and Deleted = ? order by CPid desc limit ?');
$stm->execute(array($chatroomid, $lastpost, $deleted, $limit));
$posts = $stm->fetchAll();
// now you have all requested posts in $posts array
于 2013-03-14T05:36:05.677 回答