为什么我的代码不在数据库中存储数据?我已删除所有发生的错误。
<html><body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="sample";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
echo "error";
}
echo "Connected successfully";
if(isset($_POST['submit']))
if(isset($_POST['submit'])){$Name=$_POST['name'];$age=$_POST['age'];}
$sql = "INSERT INTO input1 (Name,age) VALUES (Name,age)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<form action="" method="post">
First name:<br>
<input type="text" name="name"><br>
Age:<br>
<input type="text" name="age">
<input type="submit" name="Submit">
</form>
</body></html>
答案 0 :(得分:2)
您没有将变量用作要插入数据库的值。你应该使用准备好的声明。
$sql = "INSERT INTO input1 (Name, age) VALUES (?, ?)";
$stmt = mysqli_prepare($conn, $sql) or die(mysqli_error($conn));
mysqli_stmt_bind_param($stmt, "si", $Name, $age);
if (mysqli_stmt_execute($stmt)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_stmt_error($stmt);
}
此外,所有这些代码都应该在if (isset($_POST['submit']))
块内。否则,当用户尚未提交表单时,您将尝试将空变量插入数据库。