這是HTML表單(register.php):停止輸入框中的空值插入到我的數據庫中? 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);
?>
這裏的問題:
如果所有輸入字段都有一個值,我想將輸入的值提交到我的數據庫中,但是當我在檢查它們是否爲空時使用了模具函數時,它會殺死腳本。如果一個或多個字段爲空,我只想要將它插入到我的數據庫中&顯示一條錯誤消息,指出哪個字段爲空。我不知道如何解決這個問題,任何幫助將不勝感激。
引用此URL:http://www.w3schools.in/php-tutorial/form-validation/ – PravinS
1.將所有錯誤存儲在數組中。如果數組是空的,則插入數據庫,否則打印數組內容。 – FirmView
您可能會收到一些評論,告訴您注意SQL注入和安全性。這是你應該關注的一個問題。另一個問題是,檢查表單字段的來源是否是一個更好的主意,例如,通過客戶端瀏覽器中的一些JavaScript/jQuery驗證程序。這樣,您可以在出現錯誤(或缺失值)的情況下爲用戶提供更快的響應,並保持服務器不必要的流量。 – cars10m