我有一个将输入数据传递到处理页面的表单。然后,此处理表单检查数据库中是否已存在电子邮件和用户名。如果他们这样做,报告错误,我遇到的问题是,如果错误报告什么,那么去执行sql insert查询否则回显错误。除了将数据插入数据库之外,我可以使其中的大部分工作。任何人都可以帮我看看我的代码中的错误吗?
处理页面:
<?php
session_start();
list($username,$email,$clubname, $hash) = $_SESSION['data'];
unset($_SESSION['data']);
include_once 'db_connect.php';
$usernameErr = $emailErr = "";
$password = $hash;
$databaseErr = 'cannot connect to database';
$query1 = mysqli_query($mysqli, "SELECT * FROM members WHERE email='".$email."'");
if(mysqli_num_rows($query1) > 0){
// echo 'email already exists';
$usernameErr = "username already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query1))
{
die('Error: ' . mysqli_error($mysqli));
}
}
$query2 = mysqli_query($mysqli, "SELECT * FROM members WHERE username='".$username."'");
if(mysqli_num_rows($query2) > 0){
// echo 'username already exists';
$emailErr = "email already exists";
}else{
// do something
if (!mysqli_query($mysqli,$query2))
{
die('Error: ' . mysqli_error($mysqli));
}
}
if ($usernameErr == "" && $emailErr == "" ) {
$sql = mysqli_query($mysqli, "INSERT INTO members (username, email, password, clubname) VALUES ('$username', '$email', '$password', '$clubname')");
if (!mysqli_query($mysqli,$sql)) {
die('Error: ' . mysqli_error($mysqli));
}
echo "1 record added";
}
else {
echo $usernameErr.'<br/><br/>';
echo $emailErr.'<br/><br/>';
}
答案 0 :(得分:1)
我想出了这个,一个简单的骨架,只是编辑以适应你。不要忘记哈希密码参数。
function emailEmailExists($emall) {
if(mysqli_num_rows($email) >= 1) {
return 1;
} else {
return 0;
}
}
function usernameExists($username) {
if(mysqli_num_rows($username) >= 1) {
return 1;
} else {
return 0;
}
}
function insertUser($username, $password, $email, $otherField, $otherField, ) {
if(checkEmailExists($email) == 1) {
echo 'Email in use!';
} else if(usernameExists($username) == 1){
echo 'Username in use!';
} else {
$insertUser = mysqli_query($yourQuery);
if($insertUser) {
echo 'User created!';
} else {
// Give error.
}
}
}
修改强>
如何创建数据库连接,删除凭据并显示。