0

我编写了这个简单的 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.");

为什么不执行查询?

4

3 回答 3

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 注入的大门。请学习并使用准备好的语句

使用准备好的语句,您的代码可能看起来像

...
$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;
}
于 2013-08-03T21:08:11.333 回答
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');
于 2013-08-03T21:08:16.067 回答
1

不能说你得到了什么错误,但尝试使用像这样的单引号插入语句

$query="INSERT INTO users(username,firstname,lastname,email,password,gender,age) VALUES('$username','$firstname','$lastname','$email','$password','$gender','$age')";

还要防止 SQL 注入(非常重要!!)。

于 2013-08-03T21:10:22.000 回答