简体   繁体   English

检查数据库中是否已经存在用户名和电子邮件

[英]Check if a username and email already exists in my database

I am new to PHP and I would like to check whether or not a username or email already exists in my database. 我是PHP的新手,我想检查数据库中是否已经存在用户名或电子邮件。 If it does, I would like to redirect back to my signup page. 如果可以,我想重定向回我的注册页面。 The code I have works to add users but I cannot figure out how to check if the username and email exist. 我拥有的代码可以添加用户,但是我无法弄清楚如何检查用户名和电子邮件是否存在。 I don't want to make either the primary key Please help!!! 我既不想做主键,也请帮忙!!! This is the code that I have now from the book I am using: 这是我现在使用的书中的代码:

<?php
require_once "app_config.php";
require_once "database_connection.php";

$upload_dir = HOST_WWW_ROOT . "uploads/profile_pics/";
$image_fieldname = "user_pic";

//Potential PHP errors
$php_errors = array(1 => 'Maximum file size in php.ini exceeded',
                    2 => 'Maximum file size in HTML form exceeded',
                    3 => 'Only part of the file was uploaded',
                    4 => 'No file was selected to upload');

$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$username = trim($_REQUEST['username']);
$password = trim($_REQUEST['password']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
$facebook_url = str_replace("facebook.org", "facebook.com", trim($_REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if($position === false) {
    $facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if($position === false) {
    $twitter_url = $twitter_url . $twitter_handle;
} else {
    $twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}

//Make sure we didn't have an error uploading the image
($_FILES[$image_fieldname]['error'] == 0)
    or handle_error("the server couldn't upload the image you selected",
                    $php_errors[$_FILES[$image_fieldname]['error']]);

// Is this file the result of a valid upload?
@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
    or handle_error("you were trying to do something naughty. Shame on you!",
                    "Uploaded request: file named " .
                    "'{$_FILES[$image_fieldname]['tmp_name']}'");

// Is this actually an image?
@getimagesize($_FILES[$image_fieldname]['tmp_name'])
    or handle_error("you selected a file for your picture " .
                    "that isn't an image.",
                    "{$_FILES[$image_fieldname]['tmp_name']} " .
                    "isn't a valid image file.");

//Name the file uniquely
$now = time();
while(file_exists($upload_filename = $upload_dir . $now .
                    '-' . $_FILES[$image_fieldname]['name'])) {
    $now++;
}

// Insert the image into the images table
$image = $_FILES[$image_fieldname];
$image_filename = $image['name'];
$image_info = getimagesize($image['tmp_name']);
$image_mime_type = $image_info['mime'];
$image_size = $image['size'];
$image_data = file_get_contents($image['tmp_name']);

//Insert into images query
$insert_image_sql = sprintf("INSERT INTO images " .
                        "(filename, mime_type, file_size, image_data) " .
                    "VALUES ('%s', '%s', %d, '%s');",
                        mysql_real_escape_string($image_filename),
                        mysql_real_escape_string($image_mime_type),
                        mysql_real_escape_string($image_size),
                        mysql_real_escape_string($image_data));

mysql_query($insert_image_sql)
    or die(mysql_error());

//Insert into users query
$insert_sql = sprintf("INSERT INTO users " .
                        "(first_name, last_name, username, " .
                        "password, email, " .
                        "bio, facebook_url, twitter_handle, " .
                        "profile_pic_id) " .
            "VALUES ('%s', '%s', '%s', '%s', '%s',
                    '%s', '%s', '%s', %d);",
                        mysql_real_escape_string($first_name),
                        mysql_real_escape_string($last_name),
                        mysql_real_escape_string($username),
                        mysql_real_escape_string($password),
                        mysql_real_escape_string($email),
                        mysql_real_escape_string($bio),
                        mysql_real_escape_string($facebook_url),
                        mysql_real_escape_string($twitter_handle),
                        mysql_insert_id());

//Insert user into database
mysql_query($insert_sql)
    or die(mysql_error());

//Redirect the user the page that displays user information
header("Location: show_user.php?user_id=" . mysql_insert_id());
exit();

?> ?>

select count(1) from users where email = '[INSERT USERNAME TO CHECK HERE]'

Getting 0 back means there are no users with that username. 返回0表示没有使用该用户名的用户。

You'll also want to lower case all the usernames prior to insertion to prevent 'bob' vs. 'Bob' vs. 'BOB' scenario. 您还希望在插入之前将所有用户名都小写,以防止出现“ bob”与“ Bob”与“ BOB”的情况。

First a great tip. 首先是一个很好的提示。 the mysql functions in PHP is out of date you should read something about PDO. PHP中的mysql函数已过时,您应该阅读有关PDO的一些知识。

But for now add this before your insert query. 但现在在您的插入查询之前添加此内容。

if(mysql_num_rows(mysql_query("SELECT ID FROM users WHERE email = '".  mysql_real_escape_string($email) ."')) != 0) {
  exit("email exists");
}

The safest way to do this is to have the database do the checking. 最安全的方法是让数据库进行检查。 This is called a "unique constraint", and it will cause any update or insert to fail, when it attempts to add a duplicate. 这称为“唯一约束”,当尝试添加重复项时,它将导致任何更新或插入失败。

You can easily create this constraint just by creating a unique index: 您只需创建唯一索引即可轻松创建此约束:

create unique index users_username on users(username);
create unique index users_email on users(email);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM