0

我有一个函数,它创建了一个包含对象数组的对象。但是,当我的 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;);
    }
}
4

1 回答 1

0

打破你的巢并脱钩。在嵌套之前确保单个查询首先工作。你在 //this 没有逗号,并且在错误后有一个额外的逗号

你为什么不做一个连接表

SELECT book.title, book_images.imageUrl FROM book
LEFT JOIN book_images
ON book.book_id=book_images.book_id WHERE book.book_id = ?;
于 2013-06-24T15:32:15.713 回答