gpt4 book ai didi

php - 防止在sql数据库中存储无效信息

转载 作者:行者123 更新时间:2023-11-29 09:45:39 25 4
gpt4 key购买 nike

我制作了这个表单,用户可以在其中输入各种信息,一切都很好,我也在检查不同的错误,但问题是,如果用户输入电子邮件格式无效,并且当按 sumbit 按钮时,它会给出错误无效的电子邮件格式没问题,但是我的数据库也存储了无效的电子邮件,如何防止存储一些无效的信息?我是编程新手。提前致谢。

$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";

if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$nameErr = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if(empty($_POST["adress"])){
$adressErr = "Adress is required";
}else{
$adress = $_POST["adress"];
}

if(empty($_POST["email"])){
$emailErr = "Email is required";
}else{
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["password"])){
$passwordErr = "Password is required";
}else{
$password = $_POST["password"];
}

if(empty($_POST["gender"])){
$genderErr = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}

$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();



?>

最佳答案

在顶部创建一个 bool 值

$hasError = false;

如果出现所有错误,请将 bool 值设置为 true $hasError = true;

sql查询之前:

if($hasError){
// redirect to form page -- pass the ERROR in the url as get and then show the error on form page
}
else{
// execute query code
}

最好进行服务器端检查,您也可以在客户端添加大量验证。

客户端检查

对于电子邮件,您可以使用 type='email' 而不是 type='text'。同样,您可以设置 maxlengthrequired 等以避免错误数据。

关于php - 防止在sql数据库中存储无效信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55742620/

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