以下是我的將數據插入表的腳本。我的問題只涉及在PHP中的表單驗證。PHP表單驗證
這裏是我的PHP代碼:
<?php
//Here I have defined an error variable for each of the variables in the project
$nameErr = $productErr = $priceErr = $catErr = $regionErr = "";
$product_name = $product_cond = $product_price = $product_cat = $product_region = "";
$con=mysqli_connect("localhost","*****","*****","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// here in this elseif, I check the number of characters in the field and then it is suppose to send an error (on the same page) if it does not match
elseif (strlen($_POST['product_name']) < 5) {
$productErr = "name is too short";
}
elseif (strlen($_POST['product_name']) > 10) {
$productErr = "name is too long";
}
elseif (empty($_POST['product_cond'])) {
$productErr = "product condition required";
}
else
{
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
}
mysqli_close($con);
?>
,這裏是我的html頁面:
<html>
<body>
<h3> Please enter your product information bellow: </h3>
<form action="insert_data.php" method="post">
Product name: <input type="text" name="product_name" >
// here I added this line that is suppose to do echo the error message:
<span class="error">* <?php echo $nameErr;?></span>
Condition:
<select name="product_cond">
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat">
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region">
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Tornio</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
</select>
Product price: <input type="text" name="product_price">
<input type="submit">
</form>
</body>
</html>
的問題是,這種方法還可以防止數據被插入到表中,但它確實不是給我一個錯誤,它只是給了我一個空白的屏幕。問題是什麼。 (我使用由w3school提供本例中:http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required)
嘗試在每個條件中回顯變量$ productErr .. –
您將錯誤存儲在'$ productErr'中,但您沒有在任何地方引用/回顯'$ productErr'。 –
嘗試檢查它與死而不是回聲的錯誤,然後如果該作品使字符串變量,並在一個if語句輸出在身體的某個地方 –