我正在製作一個基本的內容管理系統,並且我一直在驗證輸入到表單中的數據。PHP表單數據驗證問題
例如,一種形式是編輯主題的名稱(在導航菜單中)。該表單包含一些不同的數據,但主要關注的是「menu_name」字段(主題名稱)。
應該檢查「menu_name」中的表單提交數據,以確保它不是空的,如果它是錯誤的話。現在發生的情況是,表單驗證似乎不起作用,因爲當我沒有輸入任何內容時,腳本會繼續編輯主題名稱,在這種情況下會將其留空。
這是在表單提交執行腳本:
if (isset($_POST['submit']))
{
// Process the form
// Validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
// If errors occured, redirect
if(empty($errors))
{
// Perform update
// Assign POST data to variables
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
// 2. Perform database query
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = '{$position}', ";
$query .= "visible = '{$visible}' ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
的數據,然後由兩個自定義的驗證功能檢查,你可以看到,第二個是不是我關心的,但第一個函數validate_presences( ),這裏是功能:
function validate_presences($requried_fields)
{
GLOBAL $errors;
foreach($required_fields as $field)
{
$value = trim($_POST[$field]);
if (!has_presence($value))
{
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
你可以看到有它引用has_presence()函數,它是:
function has_presence($value)
{
return isset($value) && $value !== "";
}
如果任何人有任何錯誤的想法,任何幫助表示讚賞! 只需詢問您是否需要更多信息。 在此先感謝!
您是否在調用驗證函數之前定義了'$ errors'變量? – Pierre
$ errors = array();在驗證功能頁面的開始處定義。 – Rubixryan
嘗試返回isset($ value)&&!empty($ value);在has_presence函數中 – Pierre