gpt4 book ai didi

php - 如何检查表单中的任何字段是否为空

转载 作者:太空狗 更新时间:2023-10-29 14:41:23 24 4
gpt4 key购买 nike

我正在为我的网站构建一个登录系统,我需要一种检查表单中所有字段是否都已填写的方法。我也收到一条错误消息,说我的电子邮件格式不正确。

<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];

if(empty($firstname) || empty($lastname) || empty($username) || empty($password) ||
empty($passwordconf) || empty($email) || empty($securityq) || empty($qanswer))
{
echo "You did not fill out the required fields.";
}

$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0)
{
echo "The username you entered is already taken";
}

$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
{
echo "The email you entered is already registered";
}

if($password != $passwordconf)
{
echo "The passwords you entered do not match";
}

$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
echo "The email you entered is not in name@domain format";
}

最佳答案

当使用大表格时,我建议使用表格字段创建一个数组:

$fields = array('firstname', 'lastname', 'username', 'password', 'passwordconf', 'email', 'securityq', 'qanswer');

$error = false; //No errors yet
foreach($fields AS $fieldname) { //Loop trough each field
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
echo 'Field '.$fieldname.' misses!<br />'; //Display error with field
$error = true; //Yup there are errors
}
}

if(!$error) { //Only create queries when no error occurs
//Create queries....
}

关于php - 如何检查表单中的任何字段是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14250880/

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