我試圖在將值插入數據庫時使用預準備語句。準備好的語句不能正常工作
$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。這裏有什麼問題?
感謝
http://php.net/manual/en/pdo.prepared-statements.php - 下面的例子中,你會解決您的代碼 – Artur
您不必在準備好的語句中引用佔位符的引號。 –
是的,謝謝特雷斯科。它工作 – user3026704