这里的“正确”方法是准备好的语句。您再也不需要将字符串连接到 SQL 查询中或担心引号。
$query = $link->prepare('SELECT book_ID, Title, username as author from users,books
where users.user_ID = books.user_ID and username = ?');
$books = array();
if($query){
// Bind the value to the `?`
$query->bind_param('s', $_SESSION['sess_username']);
$query->execute();
// These variables will be created and populated with your values
$query->bind_result($book_ID, $title, $author);
while($query->fetch()){
// Each time `fetch()` is, called, the variables will be
// automagically updated with the next row's value
// This while loop will run for each row, then stop
$books[] = array(
'book_ID' => $book_ID,
'title' => $title,
'author' => $author
);
}
}
else{
die($link->error);
}
var_dump($books);
文档:http://www.php.net/manual/en/mysqli.prepare.php
编辑:如果您安装了mysqlnd 驱动程序(通常称为php-mysqlnd),那么您可以这样做:
$query = $link->prepare('SELECT book_ID, Title, username as author from users,books
where users.user_ID = books.user_ID and username = ?');
$books = array();
if($query){
// Bind the value to the `?`
$query->bind_param('s', $_SESSION['sess_username']);
$query->execute();
// This allows you to use `fetch_array` like if you had used `mysqli_query`
$result = $query->get_result();
$books = $result->fetch_all(MYSQLI_ASSOC);
}
else{
die($link->error);
}
var_dump($books);