我創建了一個註冊表單來獲取用戶的詳細信息。但是,當用戶進入細節它給這個錯誤:嘗試在MySQL中存儲用戶電子郵件和其他詳細信息時產生錯誤?
INSERT INTO players(first_name, last_name, username, email, password) VALUES (John, Doe, john.doe, [email protected], doe) 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 '@yahoo.com, aman)' at line 1
Thank you for registering!
這是我對形式的PHP代碼:
<?php
$servername="localhost";
$dbname="users";
$username="root";
$password="pass";
try {
$dbh=new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$username = $_POST["username"];
$email = $_POST["email"];
$pwd = $_POST["password"];
$sql="INSERT INTO players(first_name, last_name, username, email, password) VALUES ($first_name, $last_name, $username, $email, $pwd)";
$dbh->exec($sql);
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo "<p>Thank you for registering!</p>";
?>
我曾嘗試&抓捕獲錯誤因爲沒有它被顯示
Thank you for registering!
並且數據未存儲在數據庫中。
UPDATE: 這裏是PDO的預處理語句代碼:
<?php
$servername="localhost";
$dbname="users";
$username="root";
$password="pass";
try {
$dbh=new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$username = $_POST["username"];
$email = $_POST["email"];
$pwd = $_POST["password"];
$statement = $dbh->prepare("INSERT INTO players(first_name, last_name, username, email, password) VALUES (:first_name, :last_name, :username, :email, :pwd)";
$statement->execute(array(':first_name' => $first_name, ':last_name' => $last_name, ':username' => $username, ':email' => $email, ':pwd' => $pwd));
}
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo "<p>Thank you for registering!</p>";
?>
收到此錯誤:
Parse error: syntax error, unexpected ';' in public_html\php\reg.php on line 16
因此,如果我想將我的代碼轉換爲PDO的Prepared語句,那麼該怎麼做?你可以編輯我的代碼,並給我一個簡要的想法,如何完成。我曾嘗試過但未成功。 – Crayator
我給出的代碼應該用於腳本,用這兩個語句替換$ sql = ..和$ dbh-> exec()行。 –
獲取此錯誤:**解析錯誤:語法錯誤,意外';'在第16行public_html \ php \ reg.php ** ** – Crayator