我需要转换以下内容才能使用mysqli,但无法找到样本。有人可以这么好帮忙吗?
$books = array();
$books_query = mysql_query("SELECT * FROM book");
while ($books_row = mysql_fetch_assoc($books_query)) {
$books[] = array(
'id' => $books_row['book_id'],
'book_title' => $books_row['book_title']
);
}
return $books;
修改
我编码了;
$stmt=conn->stmt_init();
if($stmt->prepare("SELECT * FROM book"))
{
$stmt->execute();
$stmt->bind_result($r_book_id, $r_book_title);
while ($stmt->fetch())
{
....
};
}
但只是不知何故不起作用。
我的问题是我只是从.net MS SQL切换到mySQL并需要将mySQL转换为mySQLi
答案 0 :(得分:0)
正如评论中提到的那样,理想情况下我们会看到你到目前为止所尝试的内容......
你的主要资源是;
http://www.php.net/manual/en/mysqli.quickstart.php
但是,这个页面提供了一个很好的教程;
代码;
$books = array();
$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT * FROM book"
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$books[] = array(
'id' => $books_row['book_id'],
'book_title' => $books_row['book_title']
);
}
return $books;
答案 1 :(得分:0)
在你的代码中写道:
$stmt->execute();
$stmt->bind_result($r_book_id, $r_book_title);
根据文档,执行必须在 bind_result
方法之后被称为。
此外,在您致电fetch
后,您将使用$r_book_id
和$r_book_title
访问您的数据,而不是使用数组。
如果您想要更友好的用户界面,请切换到PDO。它更容易,并且它没有不同的synthax,具体取决于您使用简单或准备好的查询。
编辑:,因为你想要获取一个数组,这是诀窍:
$stmt->bind_result($r['book_id'], $r['book_title']);
$stmt->execute();
while($stmt->fetch()){
$totalResult[] = $r;//$r will contain a row as an array
}
//total result is an array with the whole result set