//如何修改以下代码,以便插入到我的表单中的值可以插入到我的mysql数据库中?我可以很好地连接到我的数据库,我的数据库称为图像,表格称为人。
//This is my insert.php file
<?php
$con=mysqli_connect("localhost","root","anble","images");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$FirstName = mysqli_real_escape_string($_POST["FirstName"]);
$LastName = mysqli_real_escape_string($_POST["LastName"]);
$Age = mysqli_real_escape_string($_POST['Age']);
$sql="INSERT INTO Persons (Name, LastName, Age);
VALUES ($FirstName, $LastName, $Age)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
// This is my form file
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input name="FirstName" type="text" value="FirstName">
Lastname: <input name="LastName" type="text" value="LastName">
Age: <input name="Age" type="text" value="Age">
<input type="submit">
</form>
</body>
</html>
// This is the error
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\xampp \htdocs\check_php\insert.php on line 10
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\check_php\insert.php on line 11
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\check_php\insert.php on line 12
Error: 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 (, , )' at line 1
答案 0 :(得分:0)
改变这个:
1)mysqli_real_escape_string()
需要2个必需参数。
2)$Firstname
和$Lastname
是字符串变量。在查询中使用时,它们应用单引号'
括起来。
$FirstName = mysqli_real_escape_string($con, $_POST["FirstName"]);
$LastName = mysqli_real_escape_string($con, $_POST["LastName"]);
$Age = mysqli_real_escape_string($con, $_POST['Age']);
$sql="INSERT INTO Persons (Name, LastName, Age);
VALUES ('$FirstName', '$LastName', $Age)";
答案 1 :(得分:0)
cahnge:
// escape variables for security
$FirstName = mysqli_real_escape_string($_POST["FirstName"]);
$LastName = mysqli_real_escape_string($_POST["LastName"]);
$Age = mysqli_real_escape_string($_POST['Age']);
为:
// escape variables for security
$FirstName = mysqli_real_escape_string($con,$_POST["FirstName"]);
$LastName = mysqli_real_escape_string($con,,$_POST["LastName"]);
$Age = mysqli_real_escape_string($con,$_POST['Age']);
mysqli_real_escape_string()
需要两个参数才能通过
1)连接
2)escapestring
您只传递了转义字符串,您需要在mysqli_real_escape_string()
中提供链接标识符。
你还需要在查询中的字符串变量中添加引号。 变化:
$sql="INSERT INTO Persons (Name, LastName, Age);
VALUES ($FirstName, $LastName, $Age)";
为:
$sql="INSERT INTO Persons (Name, LastName, Age)
VALUES ('$FirstName', '$LastName', '$Age')";