Helo。我在執行以下INSERT INTO查詢時遇到問題。 SELECT工作正常。錯誤在哪裏?如何插入數據庫(語法錯誤)
的PHP還給此錯誤消息:
Error: 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 ''id', 'reg_date', 'szoveg') VALUES (NULL, CURDATE(), 'x')' at line 1
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "db";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM Notes");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if(isset($_POST["szoveg"])){
$query = "INSERT INTO Notes ('id', 'reg_date', 'szoveg') VALUES (NULL, CURDATE(), '".$_POST["szoveg"]."')";
$stmt = $conn->prepare($query);
$stmt->execute();
}
**警告**:使用PDO時,您應該使用帶有佔位符值的[prepared statements](http://php.net/manual/en/pdo.prepared-statements.php),並將任何用戶數據作爲單獨的論點。在此代碼中,您可能會遇到嚴重的[SQL注入漏洞](http://bobby-tables.com/)。切勿使用字符串插值或連接,而應使用[準備語句](http://php.net/manual/en/pdo.prepared-statements.php),並且絕對不要將'$ _POST'或'$ _GET'數據直接放入您的查詢。有關此問題和其他問題的指導,請參閱[PHP正確方法](http://www.phptherightway.com/)。 – tadman