如果用户名字段为空,则在else条件下不返回空errro,如果条件运行良好,则在数据库中插入数据但是当我尝试返回错误时页面变为空白
<?php include "db.php"?>
<?php
if (isset($_POST['submit'])){
global $conn;
$error=array();
$username=$_POST['username'];
if($username==""){
$error="username is empty";
}
if(empty($error)){
$sql="INSERT INTO users (username,password,category)VALUES('$username','$password','$category')";
$res=mysqli_query($conn,$sql);
if($res){
echo "done";
}else{
echo "try again";
}
}else{
return $error;
}
}
?>
<html>
<body>
<fieldset style="width:30%;">
<form action="" method="post" enctype="multipart/form-data">
<label>Username</label>
<input type="text" name="username" placeholder="username" id="username" ><br>
<input type="submit" name="submit" id="submit" value="submit">
</form>
</fieldset>
</body>
</html>
答案 0 :(得分:0)
尝试使用此脚本。
<?php
if (isset($_POST['submit']))
{
global $conn;
$error=array();
$username=$_POST['username'];
if($username == ""){
$error="username is empty";
}else{
$sql="INSERT INTO users (username,password,category)VALUES('$username','$password','$category')";
$res=mysqli_query($conn,$sql);
if($res){
echo "done";
}else{
echo "try again";
}
}
//THIS IS ARRAY SO YOU HAAVE TO PRINT LIKE THIS
print_r( $error);
}
您不必再使用else语句两次。只需检查错误是否为空并运行。 快乐编码: - )
答案 1 :(得分:0)
我在执行过程中发现了很多错误,请检查以下代码。
1)它应该是empty($username)
而不是$username == ''
基本上没有关系,它可以是任何一种方法
2)你有return $error;
这意味着它只会返回打印
所以你需要使用print_r($error)
没有函数可以返回,所以你只需在表格顶部打印错误。
3)使用参数化查询而不是将变量传递给查询。
如果仍然无法正常工作,请在php标记之后取消注释这两行并检查错误
我为错误添加了一个建议,您可以在字段之后显示错误,如下所示
请检查<span>
之后添加的input
标记以及样式错误类,如颜色边框等。
<?php
//error_reporting(-1);
//ini_set('display_errors',true);
include "db.php";
if (isset($_POST['submit'])){
global $conn;
$error=array();
$username=$_POST['username'];
$password=$_POST['password'];
if(empty($username)){
$error['username']="username is empty";
}
if(empty($password)){
$error['password']="password is empty";
}
if(empty($error)){
$sql="INSERT INTO users (username,password,category)VALUES(?, ?, ?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("sss", $username,$password,$category);
if($stmt->execute())
echo "Done";
else
echo "Try Again!";
}
} else {
//print_r($error);
}
}
?>
<html>
<body>
<fieldset style="width:30%;">
<form action="" method="post" enctype="multipart/form-data">
<label>Username</label>
<input type="text" name="username" placeholder="username" id="username" ><br>
<span class='error'><?=$error['username']?></span></br />
<input type="password" name="password" placeholder="password" id="password" ><br>
<span class='error'><?=$error['password']?></span></br />
<input type="submit" name="submit" id="submit" value="submit">
</form>
</fieldset>
</body>
</html>