这是我的变量
$error=[];
$dbname=htmlspecialchars(trim($_POST["dbname"]));
$dbusername=htmlspecialchars(trim($_POST["dbusername"]));
$dbpassword=htmlspecialchars(trim($_POST["dbpassword"]));
$dbhost=htmlspecialchars(trim($_POST["dbhost"]));;
$debugging=$_POST["debugging"];
... // i got such variables many some are not belong to post as well
我想像这样显示错误
if(empty($dbname){
echo $error['$dberro']="Hey you have missed the database name";
}
if(empty($dbusername){
echo $error['$dbusernameerror']="Hey you have missed the database user name";
}
.... // i have such code many
我有这40个变量,我怎么这么容易这样做..我在静态页面或其他一些php页面上显示
if (isset($error[$dberror])){
echo "$error[$dberror]";
}
... //i have such many
代码不是那么笨重,可能有比这更好的想法
我可以得到这些想法
答案 0 :(得分:0)
你可以使用一个数组并通过它来检查..这样的东西:
$db_array = array(
'dbname' => htmlspecialchars(trim($_POST["dbname"])),
'dbusername' => htmlspecialchars(trim($_POST["dbusername"])),
etc..
etc..
);
foreach($db_array as $key => $value) {
if(empty($value)) {
echo "Hey you have missed: $key";
}
}
编辑:按照jtmanteos评论进行修正
答案 1 :(得分:0)
您可以创建第一个数组来存储变量及其描述 另一个存储数据:
<?php
$error=[];
//data associate var and its description
$data[
'dbname'=>'database name',
'dbusername'=>'database user name',
'dbpassword'=>'database password',
'dbhost'=>'database host',
'debugging'=>'debugging'
];
//values store the values in an array
$values['dbname']=htmlspecialchars(trim($_POST["dbname"]));
$values['dbusername']=htmlspecialchars(trim($_POST["dbusername"]));
$values['dbpassword']=htmlspecialchars(trim($_POST["dbpassword"]));
$values['dbhost']=htmlspecialchars(trim($_POST["dbhost"]));;
$values['debugging']=$_POST["debugging"];
//test values
foreach($data as $var=>$description){
if(empty($values[$var]){
echo $error[$var]="Hey you have missed the ".$description;
}
}
答案 2 :(得分:0)
这个怎么样:
<?php
foreach($_POST as $key => $value) {
$$key = htmlspecialchars(trim($_POST["dbname"]));
if(empty($$key)) {
echo "Hey you have missed: $key";
}
}
?>