【发布时间】:2016-09-04 17:23:37
【问题描述】:
请谁能帮我指出这段代码中的错误?我是 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>
【问题讨论】:
-
非常感谢。它工作得很好。上帝保佑你、你的家人以及所有导致堆栈溢出的人。
标签: php html css function mysqli