我正在使用下面的脚本验证表单数据。 当我提交表单时,如果有任何错误,错误消息正确显示,但如果没有错误和验证成功,我尝试回显变量来测试脚本,但脚本只显示这个:[] 请检查代码并帮我解决这个问题。
<?php
//included files
include("./includes/connect.php");
include("./includes/functions.php");
$errors = array();
//checking if user have submitted the form
if(isset($_POST['submitted'])) {
//validating and cleaning submitted form data ...
if (isset($_POST['name']) && !empty($_POST['name'])) {
if(preg_match("/^[a-zA-Z ]{2,20}$/", strip_trim($_POST['name']))) {
$cln_name = clean_data($_POST['name']);
} else {
$_POST['name'] = FALSE;
$errors[] = "The name you entered is not valid";
}
} else {
$errors[] = "You have not enter your name!";
}
if(isset($_POST['email']) && !empty($_POST['email'])) {
$cln_email = filter_var($_POST['email'] , FILTER_SANITIZE_EMAIL);
if(filter_var($cln_email, FILTER_VALIDATE_EMAIL)) {
$cln_email = clean_data($cln_email);
} else {
$_POST['email'] = FALSE;
$errors[] = "The email you entered is not valid";
}
} else {
$errors[] = "You have not provide you email!";
}
if(isset($_POST['plate_num']) && !empty($_POST['plate_num'])) {
if(ctype_alnum($_POST['plate_num']) && strlen($_POST['plate_num']) >= 5) {
$cln_plate_num = clean_data($_POST['plate_num']);
} else {
$_POST['plate_num'] = FALSE;
$errors[] = "The plate number you provided is not a valid plate number";
}
} else {
$errors[]= "You have not provide a plate number";
}
//checking for errors and printing errors..
if (count($errors > 0)) {
$errors_to_json = json_encode($errors);
echo $errors_to_json;
//foreach ($errors as $error) {
//echo $error . "<br />";
//}
} else {
echo $cln_name . "<br />";
echo $cln_email . "<br />";
echo $cln_plate_num;
}
} else {
echo "You did not submit the form!";
}
?>
此脚本仅返回此内容: []
有什么想法吗?
functions.php:
<?php
function clean_data($data) {
if(function_exists('mysql_real_escape_string')) {
global $dbc;
$data = mysql_real_escape_string(trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string(trim($data));
$data = strip_tags($data);
}
return $data;
}
function strip_trim($data) {
$data = stripslashes(trim($data));
return $data;
}
?>
答案 0 :(得分:1)
你的if条件有问题:
//checking for errors and printing errors..
if (count($errors > 0)) {
...
这将始终返回TRUE
,因为$error = []
和count([] > 0)
会导致TRUE
这就是为什么你总是最终:
$errors_to_json = json_encode($errors);
echo $errors_to_json;
// Will indeed display '[]' because json_encode([]) is '[]'
我相信你的意思是:
if (count($errors) > 0) {
...