准备好的陈述不能正常工作

时间:2013-11-24 10:32:40

标签: php oop

我在db中插入值时尝试使用预准备语句。

     $this->db = new Database();

    if(!empty($_POST['first_name'])){
        $this->first_name = $_POST['first_name'];
    }
    if(!empty($_POST['second_name'])){
        $this->second_name = $_POST['second_name'];
    }
    if(!empty($_POST['last_name'])){
        $this->last_name = $_POST['last_name'];
    }
    if(!empty($_POST['course'])){
        $this->course = $_POST['course'];
    }
    if(!empty($_POST['math'])){
        $this->math = $_POST['math'];
    }
    if(!empty($_POST['programming'])){
        $this->programming = $_POST['programming'];
    }
    if(!empty($_POST['english'])){
        $this->english = $_POST['english'];
    }
    if(!empty($_POST['history'])){
        $this->history = $_POST['history'];
    }
    try {
    $this->stmt = $this->db->dbh->prepare("INSERT INTO students (first_name,second_name,last_name,course) VALUES (':first_name',':second_name',':last_name',':course')");
    $this->stmt->bindValue(':first_name', $first_name, PDO::PARAM_INT);
    $this->stmt->bindValue(':second_name', $second_name, PDO::PARAM_STR);
    $this->stmt->bindValue(':last_name', $last_name, PDO::PARAM_STR);
    $this->stmt->bindValue(':course', $course, PDO::PARAM_STR);
    $this->stmt->execute();
    //$this->db->insertQuery("INSERT INTO objects (student_id,math,programming,english,history) VALUES ('','".$this->math."','".$this->programming."','".$this->english."','".$this->history."')");
    //$data = $this->db->stmt->fetchAll($q);
    //$this->view->render('index','template',$data);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
        }

它不起作用,表中的值为:first_name,:second_name,:third_name。这有什么不对?

由于

3 个答案:

答案 0 :(得分:0)

准备好的陈述工作正常,而你的代码却没有。

更改

$this->db->insertQuery("INSERT INTO students (id,first_name,second_name,last_name,course) VALUES ('',':first_name',':second_name',':last_name',':course')",array(':first_name'=>$this->first_name,':second_name'=>$this->second_name,':last_name'=>$this->last_name,':course'=>$this->course));

$this->db->insertQuery("INSERT INTO students (id,first_name,second_name,last_name,course) VALUES ('',':first_name',':second_name',':last_name',':course')",array('first_name'=>$this->first_name,'second_name'=>$this->second_name,'last_name'=>$this->last_name,'course'=>$this->course));

请注意,要传递的值数组中缺少:

答案 1 :(得分:0)

从数组键中删除“:”。

答案 2 :(得分:0)

你能尝试一下吗,我已经从查询中删除了id列

 $this->db->insertQuery("INSERT INTO students (first_name,second_name,last_name, course)      
 VALUES (':first_name',':second_name',':last_name',':course')",
 array('first_name'=>$this->first_name,'second_name'=>$this->second_name,
'last_name'=>$this->last_name,'course'=>$this->course));