我第一次使用PDO时遇到一些问题。插入后出现错误:
<?php
require_once '_dbconnect.php';
// Attempt insert query execution
try{
// Create prepared statement
$sql = "INSERT INTO `entrysubmissions` (boxnum, entryname, entryemail) VALUES (:boxnum, :entryname, :entryemail );";
$stmt = $conn->prepare($sql);
// Bind parameters to statement
$stmt->bindParam(':boxnum', $_REQUEST['entryboxid'], PDO::PARAM_INT);
$stmt->bindParam(':entryname', $_REQUEST['entryname'], PDO::PARAM_STR);
$stmt->bindParam(':entryemail', $_REQUEST['entryemail'], PDO::PARAM_STR);
// Execute the prepared statement
$stmt->execute();
echo "Entry Submitted Successfully.";
print $_REQUEST['entryboxid'];
print $_REQUEST['entryname'];
print $_REQUEST['entryemail'];
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
?>
我遇到错误,但是该行已成功插入。我一定在做一些明显的错误,但是我找不到它。正确的值将插入表中。
ERROR: Could not able to execute INSERT INTO `entrysubmissions` (boxnum, entryname, entryemail) VALUES (:boxnum, :entryname, :entryemail );. SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':boxnum, :entryname, :entryemail )' at line 1
非常感谢您的帮助。我确实尝试过,但是今天看来我在googlefu上失败了。
您正在尝试执行两次查询。
// First here
$stmt->execute();
echo "Entry Submitted Successfully.";
print $_REQUEST['entryboxid'];
print $_REQUEST['entryname'];
print $_REQUEST['entryemail'];
// Then again here
$conn->exec($sql);
删除最后一个:
$conn->exec($sql);
您应该被设置。
您的代码很好,只需从代码中删除$ conn-> exec($ sql);,您将执行两次,这就是为什么会出错的原因。