我有一个函数创建了一个包含对象数组的对象。 但是,当我的sql语法出错时,错误不会显示。 当我将$ queryGetImages中的book_images更改为book_images_blabla时,准备失败并调用else。 在那里我抛出一个错误,但首先我必须关闭$ stmt对象。 然而。当我关闭它时,错误不再可用。 怎么可能?因为错误是在$ stmtImages上抛出的,而不是在$ stmt?
上public function getBook($number){
$query = "select title from book where book_id = ?";
if ($stmt = $this->database->getConnection()->prepare($query)) {
$stmt->bind_param("i",$number);
$stmt->execute();
$stmt->bind_result($title);
$stmt->store_result();
if(($stmt->num_rows) > 0){
$stmt->fetch();
$book = new Book($title);
//get images
$queryGetImages = "select imageUrl from book_images where book_id = ?";
if ($stmtImages = $this->database->getConnection()->prepare($queryGetImages)) {
$stmtImages->bind_param('i',$number);
$stmtImages->execute();
$stmtImages->bind_result($imageUrl);
$stmtImages->store_result();
if(($stmtImages->num_rows) > 0){
$images = array();
while($stmtImages->fetch()){
$image = new Image($imageUrl);
array_push($images,$image);
}
$book->images = $images;
}
$stmtImages->close();
}else{
echo $this->database->getConnection()->error; //this works
$stmt->close();
echo $this->database->getConnection()->error; //this doesn't
throw new Exception('Error: ' . $this->database->getConnection()->error;);
}
}
$stmt->close();
return $book;
}else{
throw new Exception('Error: ' . $this->database->getConnection()->error;);
}
}
答案 0 :(得分:0)
打破你的巢和脱毛。在嵌套之前确保单个查询首先工作。你没有逗号//这不是 错误之后的额外逗号
为什么不进行联接表
SELECT book.title, book_images.imageUrl FROM book
LEFT JOIN book_images
ON book.book_id=book_images.book_id WHERE book.book_id = ?;