如何判断用户是否已将表格的一部分留空
问题描述:
我已经创建了一个允许用户在我的数据库中输入不同产品的php页面。我已经设置了不同的验证,可以正常工作,但无法弄清楚如何判断用户是否已将表格的一部分留空或整个项目为空。他们有三个文本框,用于标识,项目和成本。有谁知道我可以去看看这些文本框中的每一个都是空白的吗?谢谢如何判断用户是否已将表格的一部分留空
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Adding Products</title>
</head>
<body>
<?php
$db_server = "server";
$db_username = "name";
$db_password = "pass";
$con = mysql_connect($db_server, $db_username, $db_password);if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$database = "Product";
$er = mysql_select_db($db_username);
if (!$er)
{
print ("Error - Could not select the database");
exit;
}
$tbl_name ="Product";
$ProductCode=$_POST['ProductCode'];
$Description=$_POST['Description'];
$Price=$_POST['Price'];
$ProductCode=mysql_real_escape_string($ProductCode);
$Description=mysql_real_escape_string($Description);
$Price=mysql_real_escape_string($Price);
$status = "OK";
if(strlen($ProductCode)>10)
{
echo('Your product code can only be a max of ten characters<BR>');
$status= "NOTOK";
}
if(strlen($Description)>40)
{
echo('Your description of the product can only be 40 characters<BR>');
$status ="NOTOK";
}
if(is_float($Price))
{
$english_format_number = number_format($Price); //Changing number to floating point
//echo ('Your number must be in floating point.<BR>');
//$status ="NOTOK";
}
if($status<>"OK")
{
echo('Some of your inputs were not in the correct format.<BR>');
}
else
{
$sql="INSERT INTO $tbl_name(Product_Code, Description, Price)VALUES('$ProductCode', '$Description', '$Price')";
$result=mysql_query($sql);
echo ('Your items have been inserted into the databae.');
}
?>
答
您可能正在寻找empty()
。所以基本上你需要的是这样的:
if (empty($_POST['field1']) || empty($_POST['field2'])) {
// handle error
}
答
if (!empty($_POST['ProductCode'])) {
$ProductCode = $_POST['ProductCode'];
} else {
echo 'Please, fill in Product Code field';
}
答
empty()
是你所追求的,我想。
例如
if (empty($_POST['ProductCode'])) {
// product code is empty
}
有,然而,一个警告此:empty()
认为'0'
(包含零的字符串)是空的。如果这是你的一个字段一个有效的值,你会过得更好这样做:
if (!isset($_POST['ProductCode']) || trim($_POST['ProductCode']) === '') {
// product code is empty
}
答
if(!isset($ProductCode) && empty($ProductCode))
{
echo('your message');
$status= "NOTOK";
}
if(!isset($Description) && empty($Description))
{
echo('your message');
$status ="NOTOK";
}
if(!isset($Price) && empty($Price))
{
echo('your message');
//$status ="NOTOK";
}
编辑:这可能有助于
+0
这不起作用。变量不能为空,并且同时有超过10个字符。你需要将逻辑和'&&'转换为或'||'。 –
+0
thx没有看到即将修改它 –
你不需要做'isset()函数在'与'emtpy()'结合使用 - 它会检查你,并且不会抛出错误。 – DaveRandom
你说得对,修好了。 – Constantine