Mysqli准备好的声明每次失败

时间:2014-08-02 06:39:49

标签: php mysql mysqli prepared-statement

Mysqli prepare语句在每次尝试中失败。我尝试了很多东西,但他们没有工作。我的代码是:

<?php
include_once 'config.php';
class Database {
function insertImage($title,$desc,$thumbnail_path,$image_path, $uploaded_by){
    $link = mysqli_connect('DB_SERVER', 'DB_USER', 'DB_PASSWORD', 'DB_NAME');

    /* check connection */
    if (!$link) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    else{
        $query = "INSERT INTO photos (title, description, thumbnail,image,uploaded_by) VALUES(?, ?, ?, ?, ?)";
        $stmt = mysqli_prepare($link,$query);
        if(!$stmt){
            die("NO statement");
        }
        else
        {
            mysqli_stmt_bind_param($stmt,'sssss',$title,$desc,$thumbnail_path,$image_path,$uploaded_by);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

        }
        mysqli_close($link);

    }

}

和函数运行如下:

$db = new Database();
            $db->insertImage($post_title,$post_description,$thumb_path,$full_path,$post_description);

请指导我哪里出错了。
感谢。

1 个答案:

答案 0 :(得分:0)

您没有正确使用课程。我建议你找一个关于面向对象编程的教程,这样你就会明白。这是你的课程以基本的OO格式重写。

<?php
include_once 'config.php';
class Database {
    private $conn;//the class property holding your mysqli database object
    function __construct(){
        $this->conn = mysqli_connect('DB_SERVER', 'DB_USER', 'DB_PASSWORD', 'DB_NAME');//construct your $mysqli object.
    }
    public function insertImage($title,$desc,$thumbnail_path,$image_path, $uploaded_by){
        try{
            $query = $this->conn->query("START TRANSACTION;");//start the transaction
            $stmt = $this->conn->prepare("INSERT INTO photos (title, description, thumbnail,image,uploaded_by) VALUES(?, ?, ?, ?, ?);");//OO prepared statement
            $stmt->bind_param('sssss',$title,$desc,$thumbnail_path,$image_path,$uploaded_by);//bind params 
            if(!$stmt->execute()){ //if statement doesn't execute
                throw new Exception('problem with query');//throw execption, the statement failed to execute.
            }else{
                $stmt->close();//close the statement
                $query = $this->conn->query("COMMIT;");//commit the transaction
            }
        catch(Exception $e){
            $query = $this->conn->query("ROLLBACK;");//roll the database back removing any partially commited data.
            return $e->getMessage();
        }

    }
}