我正在尝试将用户的数据输入数据库。我认为地址中的逗号导致错误。地址为“12/8,nazimabad
”
<?php
$full_name = $_POST["fullname"];
$email = $_POST["email"];
$password = $_POST["password"];
$full_address = $_POST["address"];
$city = $_POST["city"];
$age = $_POST["age"];
$contact_number = $_POST["number"];
$gender = $_POST["gender"];
$education = $_POST["education"];
?>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
以下是我遇到的错误:
错误:
INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education) VALUES (Fahad Uddin, fahaduddinpk@gmail.com, sathdo1976,3c,12/8,nazimabad,karachi,25,03362820153,male,male)
您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在第2行'Uddin,fahaduddinpk @ gmail.com,sathdo1976,3c,12/8,nazimabad,karachi,25,033628201'附近使用正确的语法
答案 0 :(得分:4)
正如其他人所说,您的代码很容易受到SQL注入攻击。您应该考虑使用参数化查询:
$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
有关更多信息,请参阅MySQLi prepared statements上的PHP手册。
答案 1 :(得分:2)
您需要在SQL语句中引用字符串;
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ('$full_name', '$email', '$password','$full_address','$city',$age,'$contact_number','$gender','$education')";
注意包含字符串的所有变量的单引号。我可能有点不对,因为我不知道值或表结构。 但是只引用进入日期或文本字段的所有值。
为了避免其他问题和安全风险,您应该使用mysqli_real_escape_string
(至少)。
在所有赋值语句中,将值包装在mysqli_real_escape_string
$full_name = mysqli_real_escape_string($conn, $_POST["fullname"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
...
请注意,这需要在变量赋值之前设置数据库连接,因此您必须稍微重新组织代码。
rink.attendant.6的答案是适应代码的正确方法。