从mysqli预处理语句创建一个数组

时间:2014-04-19 00:29:00

标签: php mysql mysqli

我有一个简单的脚本,我试图理解为什么它不起作用,以及如何得到我想要的。

我想得到的是一个数组,称之为$results并将数据存储如下

$results ->
    $row1 ->
        $field1
        $field2
        $field3
        $field4
        $field5
    $row2 ->
        $field1
        $field2
        $field3
        $field4
        $field5

等...

但我甚至无法让mysqli完成循环结果,这是我的代码......

require_once ('lib/constants.php');
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to Database.');

$query = "SELECT * FROM employees LIMIT 0, 20";

if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$row = array();
stmt_bind_assoc($stmt, $row);

while($stmt->fetch()) {
    var_dump($row);
}
}

2 个答案:

答案 0 :(得分:0)

请在PHP.net上查看mysqli_result::fetch_assoc方法以便更好地理解。

以下是一个简单的例子

require_once ('lib/constants.php');
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to Database.');

$query = "SELECT * FROM employees LIMIT 0, 20";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        echo $row['myfield'];
    }

    /* free result set */
    $result->free();
}

答案 1 :(得分:-1)

您应该检查mysqli_result:::fetch_all而不是mysqli_result :: fetch_assoc

$query = "SELECT * FROM employees LIMIT 0, 20";

if ($result = $mysqli->query($query)) {
    $array_assoc = $result->fetch_all();

    /* free result set */
    $result->close();
}