【发布时间】:2013-08-07 05:11:26
【问题描述】:
这是html表单(register.php):
<html>
<body>
<form action="handle_registration.php" method="post">
<fieldset><legend>Enter your
information in the form below:</legend>
First Name: <input type="text" name="fname" size="20" maxlength="40"><br>
Last Name: <input type="text" name="lname" size="20" maxlength="40"><br>
Username: <input type="text" name="uname" size="20" maxlength="40"><br>
Password: <input type="text" name="pword" size="20" maxlength="40"><br>
<input type="submit" name="submit" value="submit my info">
</form>
</body>
</html>
这是处理注册的php脚本(handle_registration.php):
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "registration_info";
$con = mysqli_connect("$db_host", "$db_user", "$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Make sure all of the input boxes have a value:
if (empty($fname)) {
die('You forgot to enter your first name!');
}
if (empty($lname)) {
die('You forgot to enter your last name!');
}
if (empty($uname)) {
die('You forgot to choose a username!');
}
if (empty($pword)) {
die('You forgot to choose a password!');
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);
?>
问题来了:
如果所有输入字段都有值,我想将输入的值提交到我的数据库中,但是当我在检查它们是否为空后使用 die 函数时,它会终止脚本。如果一个或多个字段为空,我只想杀死部分将其插入我的数据库并显示一条错误消息,告知哪个字段为空。我不知道如何解决这个问题,任何帮助将不胜感激。
【问题讨论】:
-
1.将所有错误存储在一个数组中。如果数组为空,则插入数据库,否则打印数组内容。
-
您可能会收到一些 cmets,告诉您注意 SQL 注入和安全性。这也是您应该关注的一个问题。另一个问题是,检查表单字段的来源是否是一个更好的主意,即通过客户端浏览器中的一些 JavaScript/jQuery 验证器。通过这种方式,您可以在出现错误(或缺失值)时为用户提供更快的响应,并避免来自服务器的不必要流量。
标签: php forms mysqli registration