我正在尝试学习如何编码,我试图将一个基本表单插入到本地使用xampp的mysql服务器中,我只是不确定我在做什么错。
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
<title> My Practice Page </title>
</head>
<body>
<?
$first_name = '';
$last_name ='';
$city ='';
?>
$db = MYSQLI_CONNECT('localhost','root','','practiceforms');
$sql = "INSERT INTO users (first name, last name, city) VALUES
('$first_name', '$last_name', '$city')";
mysqli_query($db, $sql);
mysqli_close($db);
echo '<p> User added. </p>';
<form method="post" action="">
First Name: <input type="text" name="First Name" value="<?php $first_name;? >" <br>
Last Name: <input type="text" name="Last Name" value ="<?php $last_name;?>"<br>
City: <input type ="text" name="city" value=<?php $city; ?>" <br>
<input type="submit" name="submit" value="submit">
</body>
</html>
答案 0 :(得分:2)
您发布的代码存在一些问题。
首先,并非所有代码都在php标记内。
/usr/include
其次,每次运行此页面时,它都会尝试将内容插入到数据库中。用
包装代码<?
$first_name = '';
$last_name ='';
$city ='';
?> // THIS LINE SHOULD BE AT THE END OF THIS BLOCK
$db = MYSQLI_CONNECT('localhost','root','','practiceforms');
$sql = "INSERT INTO users (first name, last name, city) VALUES
('$first_name', '$last_name', '$city')";
mysqli_query($db, $sql);
mysqli_close($db);
echo '<p> User added. </p>';
// RIGHT HERE
?>
第三,你需要设定你的价值。
if (isset($_POST['submit'])) {
// all your code goes inside this
// so it only fires when a users presses submit
$first_name = ''; // i think you get the picture...
}
关于最后一个的通知。如果由于某种原因,未提交first_name输入(例如,在提交表单时输入不在页面上),那么当您尝试使用它时,PHP会向您大吼大叫$first_name = $_POST['first_name'];
未设置,因此您应该这样做。
$_POST['first_name']