mysqli返回所有相同的记录


mysqli returns all identical records

下面的代码应该从表中检索所有记录并将它们返回到数组。它确实返回了正确数量的记录,但所有记录都是相同的。有人知道问题出在哪里吗?

function list_book() {
$username = "user";
$password = "pwd";
$conn =  mysqli_connect('localhost', $username, $password, 'db') or die('Could Not Connect' . mysql_error());
$stmt = $conn->stmt_init();
if ($stmt->prepare("SELECT * FROM book")) {
    $stmt->bind_result($r['book_id'], $r['book_title']);
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        exit();
    }
    while($stmt->fetch()){
        $book[] = $r;
    }
    print_r($book);     //**** added purposely to examine the content of the array
    exit();
    return $book;
}
mysqli_close($conn);

}

必须在执行语句后绑定参数。。。看见http://www.php.net/manual/en/mysqli-stmt.bind-result.php

此外,我不知道你是否可以绑定到数组的元素。。。

在你的if语句中试试这个。。。

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    exit();
}
$stmt->bind_result($book_id, $book_title);
while($stmt->fetch()){
    $book[] = array($book_id, $book_title);
}

不要使用难看的mysqli
使用一些可以在2行中完成所有工作的助手类,luke-safemysql可以完成

function list_book() {
    global $db; // NEVER connect in the function, connect once and then use ONE connection
    return $db->getAll("SELECT * FROM book");
}

或者至少使用PDO,如果你想坚持使用原始的API
但忘了mysqli吧,它不可用。

问题是,只有一个数组$r。每次调用$stmt->fetch()时,该数组的参数都会被覆盖,并将其再次附加到$book-数组中。

一种可能的解决方案:(不一定是最好的)

$stmt->bind_result($book_id, $book_title);
...
while($stmt->fetch()){
    $book[] = array($book_id, $book_title);
}

我想我通过在while循环中添加以下内容解决了这个问题。感谢大家的贡献!!!:)

foreach( $r as $key=>$value ) {
    $row_tmb[ $key ] = $value;
}
$book[] = $row_tmb;

表是否有重复记录?

如果是这样,稍微修改一下SQL可能会有所帮助,例如:SELECT DISTINCT book_id, book_title FROM book

而不是显式的"绑定",也许$r = $stmt->fetch_assoc()

然后,您可以将$r['book_title'](或任何字段)收集到您的数组中。