我使用Unity表单与PHP一起将数据发送到数据库,我可以成功输入信息并到达数据库,但问题是如果字段为空,它也会发送数据。
我正在尝试使用isset方法来防止这种情况,但它似乎并没有起作用。有人可以为我仔细检查一下吗?
到达数据库的数据图像
统一形式的形象
<?php
if(!isset($_POST['usernamePost'], $_POST['passwordPost'], $_POST['emailPost']))
{
echo "This is not working";
}
else
{
//Enter the data into the database
$username = filter_var($_POST['usernamePost'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['passwordPost'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['emailPost'], FILTER_SANITIZE_STRING);
//variable for connection
$servername = "localhost";
$server_username = "root";
$server_password = "";
$dbName = "ontrigger_game";
try
{
//connection to the database
$dbhandle = mysqli_connect($servername, $server_username, $server_password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysqli_select_db($dbhandle, $dbName)
or die("Could not select database");
$sql = "INSERT INTO users (username, password, email)
VALUES ('".$username."','".$password."','".$email."')";
if(!mysqli_query($dbhandle, $sql))
{
die('Error: ' . mysqli_error());
}
echo "1 record added";
//close the connection
mysqli_close($dbhandle);
}
catch (Exception $ex)
{
}
}
?>
答案 0 :(得分:2)
您还应该使用empty()
方法检查其是否为空
if (!isset($_POST['usernamePost']) && empty($_POST['usernamePost'] )) {
// error message here
} else {
// What you want to do if not empty and is set.
}
注意:使用&&
运算符代替逗号