我写了这个简单的PHP代码来将信息插入数据库:
$cxn = mysqli_connect($host,$user,$password,$database)
or die ("Couldn't connect to server.");
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$gender = $_POST['gender'];
$age = $_POST['age'];
$query="INSERT INTO users(username,firstname,lastname,email,password,gender,age) VALUES($username,$firstname,$lastname,$email,$password,$gender,$age)";
$result = mysqli_query($cxn,$query)
or die ("Couldnt't execute query.");
为什么查询没有执行?
答案 0 :(得分:5)
您必须在字符串值周围使用引号
更改
$query="INSERT INTO users(username,firstname,lastname,email,password,gender,age)
VALUES($username,$firstname,$lastname,$email,$password,$gender,$age)";
到
$query="INSERT INTO users(username,firstname,lastname,email,password,gender,age)
VALUES('$username','$firstname','$lastname','$email','$password','$gender','$age')";
旁注:插入查询字符串而不是清理用户输入是SQL注入的一扇门。请学习并使用 prepared statements 。
使用预准备语句,您的代码可能看起来像
...
$query="INSERT INTO users(username,firstname,lastname,email,password,gender,age)
VALUES(?,?,?,?,?,?,?)";
// Prepare statement
if (!($stmt = $cxn->prepare($query))) {
echo "Prepare failed: (" . $cxn->errno . ") " . $cxn->error;
}
// Bind parameters
if (!$stmt->bind_param("sssssss", $username,$firstname,$lastname,$email,$password,$gender,$age)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
// Execute query
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
答案 1 :(得分:2)
您的查询如下:
INSERT INTO users(username,firstname,lastname,email,password,gender,age)
VALUES($username,$firstname,$lastname,$email,$password,$gender,$age)
很可能,许多值都是字符串,因此它们需要用单引号括起来。而且,很可能,变量本身并没有单引号。当然,参数替换是要走的路。但是,与此同时,您可以尝试:
INSERT INTO users(username,firstname,lastname,email,password,gender,age)
VALUES('$username', '$firstname' , '$lastname', '$email', '$password', '$gender','$age');
答案 2 :(得分:1)
不能说你得到了什么错误,但尝试使用带有单引号的插入语句
$query="INSERT INTO users(username,firstname,lastname,email,password,gender,age) VALUES('$username','$firstname','$lastname','$email','$password','$gender','$age')";
同时防止SQL注入(非常重要!!)。