![](/img/trans.png)
[英]Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax
[英]PDOException SQLSTATE[42000]: Syntax error or access violation: 1064
我正在嘗試使用php通過注冊表單填寫條目。 但是我得到了以下錯誤:
帶有消息'SQLSTATE [42000]的異常'PDOException':語法錯誤或訪問沖突:1064 SQL語法中有錯誤; 檢查與MySQL服務器版本對應的手冊,以便在''第1行'附近使用正確的語法
這是我的代碼:
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = trim($_POST['name']);
$contact= trim($_POST['contact']);
$email = trim($_POST['email']);
if(!empty($name) && !empty($contact) && !empty($email)){
try {
$conn = new PDO("mysql::host='localhost';dbname=majorproject;",'root','');
//for error reporting and throwing exceptions
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("insert into #_customerdata(customername,customercontact,customeremail) values(:name,:contact,:email)");
$stmt->bindParam(':name',$name,PDO::PARAM_STR);
$stmt->bindParam(':contact',$contact,PDO::PARAM_INT);
$stmt->bindParam(':email',$email,PDO::PARAM_STR);
if($stmt->execute()){
header('location: ../customersignup.php?status=success');
}
else{
header('location: ../customersignup.php?status=failed');
}
} catch (PDOException $e) {
echo 'CONNECTION NOT ESTABLISHED '.$e;
}
}
}
我檢查了我的代碼但找不到任何錯誤..有什么建議可以解決這個問題嗎?
按照要求。
表名#_customerdata
的#
符號應使用ticks進行轉義。
insert into `#_customerdata`
閱讀標識符限定符: http : //dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html
假設確實是表的名稱,並且#
符號不代表數值。
要么是這樣,要么重命名它,而不包含MySQL會抱怨的任何字符。
如果它仍然抱怨它,那么你將別無選擇,只能將其重命名為customerdata
。
另外,如spencer7593的評論中所述 :
OP正在使用PDO而不是已棄用的mysql_函數,OP正在使用帶有綁定占位符的預准備語句。 就個人而言,我在這個上下文中使用bindValue
而不是bindParam
。 bindParam和bindValue有什么區別?
並刪除其中一個冒號mysql::host
。
有關連接PDO的信息,請參閱手冊:
手冊中的示例:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
腳注:
你應該添加一個exit;
在每個標頭之后,否則您的代碼可能希望繼續執行。
if($stmt->execute()){
header('location: ../customersignup.php?status=success');
exit;
}
else{
header('location: ../customersignup.php?status=failed');
exit;
}
參考:
將錯誤報告添加到文件的頂部,這將有助於查找錯誤。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
旁注:顯示錯誤只能在分段中完成,而不能在生產中完成。
如果還沒有工作,請嘗試解決此問題:
$conn = new PDO("mysql::host='localhost';dbname=majorproject;",'root','');
在'mysql'和'host'之間你有'::',但它應該是':'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.