我发现当我处理有大量输入的表单时,我正在编写很多if(空...)行。将它们发送到循环中是否可以,或者这不是“最佳实践”?
<?php
$content = array("name","telephone","email");
$valid = true;
$errorMsg = "";
$successMsg = "";
if($_SERVER['REQUEST_METHOD'] === "POST"){
foreach($content as $con){
if(empty($_POST[$con])){
$valid = false;
}
}
if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$valid = false;
}
if($valid){
include_once "connect_db.php";
$name = $_POST['name'];
$telephone = $_POST['telephone'];
$email = $_POST['email'];
$sql = "INSERT INTO employees (name, telephone, email, startdate)
VALUES (?,?,?, NOW())";
$stmt = $conn->prepare($sql);
$stmt->execute([$name, $telephone, $email]);
$successMsg = "yahoo";
header("Location: main.php");
}else{
$errorMsg = "Wah wah wah";
}
}
?>
答案 0 :(得分:0)
您可以使用它来过滤空元素数组:
Fragment
因此,您可以使用第二个而不是循环,您将知道数组是否包含空值,并且您可以在验证后返回$filteredArray = array_values(array_diff($yourarrayvariable,array("null","")));
// Or You can check if it any item in array is empty
in_array("", $yourarrayvariable);
。