【问题标题】:Mysqli nested prepared statement - retrieve errorMysqli 嵌套准备好的语句 - 检索错误
【发布时间】:2013-06-24 14:58:26
【问题描述】:

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

【问题讨论】:

  • 为什么不使用 try catch throw 而不是 if else throw
  • 我在调用此函数的主页中使用 try catch。需要 if else 是因为你得到一个用于准备检查的布尔值而不是错误。

标签: php mysqli prepared-statement


【解决方案1】:

打破你的巢穴并脱钩。在嵌套之前确保单个查询首先工作。你在 //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 = ?;

【讨论】:

  • 单个查询有效,我没有使用连接,因为当您拥有多个图像时,您会得到重复的结果。当我将内部语句中的表名更改为不存在时,它不再起作用(这是正确的行为)但只有在我不关闭主 ($stmt) 语句时才能打印错误。
  • 如果您想要一张图片,请在此加入添加限制 1。您在第二个之前关闭了连接,并且两者都在同一 else 中。
  • 但是我不想要一张图片,我想要所有图片...无论如何,我不知道你的意思是在第二张之前关闭连接并且两者都相同否则,但在这个函数中连接永远不会关闭,只有语句被关闭。而在inner else中通过关闭main语句,inner语句的错误就消失了。
猜你喜欢
  • 2014-06-11
  • 1970-01-01
  • 2012-03-17
  • 2013-08-29
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
相关资源
最近更新 更多