gpt4 book ai didi

php - 即使字段为空,此 PHP 表单也通过了验证

转载 作者:行者123 更新时间:2023-11-28 16:05:27 26 4
gpt4 key购买 nike

谁能帮我指出这段代码中的错误?我是 php 新手 表单成功提交到数据库,同时显示 验证错误,当它应该在提交之前通过验证时 到 mysql 数据库。例如,当一个字段为空时,它显示 错误说该字段为空,同时插入 入数据库。

    <?php 
require_once("validation_function.php");

$errors=array();
$message = "";
$username= "";
$password= "";

if(isset($_POST["submit"])){

// open a connection to the database
include("db_connect.php");
// initialize variables with form data.

$username =trim($_POST["username"]);
$password =trim($_POST["password"]);
//validations


$field_required= array("username", "password");
foreach($field_required as $field){
$value= trim($_POST[$field]);
if(!has_presence($value)){
$errors[$field]= ucfirst($field) . " can not be blank";
}
}

$field_required_max = array("username"=>30,"password"=>8);
foreach($field_required_max as $field=> $max){
$value=trim($_POST[$field]);
if(!has_max_lenght($value,$max)){
$errors[$field]= ucfirst($field) . " is too long";
}

}


$query = "INSERT INTO test (";
$query .= " username, password";
$query .= ") VALUES (";
$query .= " '{$username}', '{$password}' ";
$query .= ")";
$result= mysqli_query($connection, $query);

if($result==1){
echo "records inserted successfully";
}else{
die("data base query failed " . mysqli_error($connection));
}

if(isset($connection)){ mysqli_close($connection); }

}
?>

<html lang="en">
<head>
<title>single page form with validations</title>
</head>
<body>
<?php echo form_errors($errors);?>
<form action="form_with_validation.php" method="post">
<p>username <input type="text" name="username" value ="" />
</p>
<p>password <input type="password" name="password" value=""></p>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>

最佳答案

试试这个:

if(empty($errors))
{
$query = "INSERT INTO test (";
$query .= " username, password";
$query .= ") VALUES (";
$query .= " '{$username}', '{$password}' ";
$query .= ")";
$result= mysqli_query($connection, $query);

if($result==1){
echo "records inserted successfully";
}else{
die("data base query failed " . mysqli_error($connection));
}

}

关于php - 即使字段为空,此 PHP 表单也通过了验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39319576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com