参见英文答案 > Error when inserting into sql database using php 1个
我正在学习MysqL.Here我有一个名为“practice”的数据库,它有一个名为“users”的表.这个表有四列.
username,password,firstname,lastname;
我有一个表单字段来获取将插入到我的MysqL表中的用户输入.但是每当我想向表中插入一个新用户时它就会出错.这个问题背后可能是什么原因?
ERROR: INSERT INTO users (username,password,firstname,lastname,)
VALUES (Nelson,101a6ec9f938885df0a44f20458d2eb4,Nelson,Mandela) 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 ‘) VALUES
(Nelson,101a6ec9f938885df0a44f20458d2eb4,Nelson,Mandela)’ at line 1
<?PHP
if(isset($_POST['name']) &&isset($_POST['password'])){
if(!empty($_POST['name']) && !empty($_POST['password'])){
$servername = $_SERVER['SERVER_NAME'];
$username = "root";
$password = "";
$dbname = "practice";
$user=htmlentities($_POST['name']);
$firstname=htmlentities($_POST['firstname']);
$lastname=htmlentities($_POST['lastname']);
$pass=md5(htmlentities(filter_var($_POST['password'],FILTER_SANITIZE_STRING)));
echo $password;
// Create connection
$conn = new MysqLi($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username,password,firstname,lastname)
VALUES ($user,$pass,$firstname,$lastname)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "ERROR: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
<form action='foreach.PHP' method='post'>
name :<input type='text' name='name' placeholder='name'></br>
firstname : <input type='text' name='firstname' placeholder='firstname'></br>
lastname : <input type='text' name='lastname' placeholder='lastname'></br>
password :<input type='text' name='password' placeholder='password'></br>
<input type='submit'>
</form>
解决方法:
删除姓氏中的尾随逗号< =
引用你的价值观,因为它们是字符串
VALUES ('$user','$pass','$firstname','$lastname')
补充说明:
您目前的代码对SQL injection开放.使用mysqli
with prepared statements或PDO with prepared statements.
您似乎也使用MD5存储密码,这是非常气馁的,它是旧的,被认为是破碎的.
对于密码存储,请使用CRYPT_BLOWFISH或PHP 5.5的password_hash()
功能.对于PHP< 5.5使用password_hash() compatibility pack
.
阅读有关MD5的这些文章:
> https://security.stackexchange.com/questions/19906/is-md5-considered-insecure
> http://en.wikipedia.org/wiki/MD5