php 检查电子邮件是否存在于 MySQL 数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22045788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:38:23  来源:igfitidea点击:

check if email exists in MySQL database

phpmysqldatabase

提问by Erwin van Ekeren

I am using the following PHP code to store data in my MySQL database, everything works perfect but I would like to build in a check; if the email already exists in the database then redirect to another page. (I'm a rookie when it comes to PHP)

我正在使用以下 PHP 代码将数据存储在我的 MySQL 数据库中,一切正常,但我想建立一个支票;如果电子邮件已存在于数据库中,则重定向到另一个页面。(我是 PHP 菜鸟)

<?php

  if(empty($_POST['name']))
  {} else {

  define('DB_NAME', 'dbname');
  define('DB_USER', 'dbuser');
  define('DB_PASSWORD', 'dbpass');
  define('DB_HOST', 'host');

  $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

  if (!$link) { die('could not connect: ' . mysql_error()); }

    $db_selected = mysql_select_db(DB_NAME, $link);

  if (!$db_selected) { die('can not use ' . DB_NAME . ': ' . mysql_error()); }

  $sql="INSERT INTO game (name, lastname, company, email, time) VALUES
('".$_POST['name']."','".$_POST['lastname']."','".$_POST['company']."','".$_POST['email']."','".$_POST['time']."')";

  if (!mysql_query($sql)) { die('Error: ' . mysql_error()); }

  mysql_close();

  }

?>

回答by Magictallguy

if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    exit('Invalid email address'); // Use your own error handling ;)
}
$select = mysqli_query($connectionID, "SELECT `email` FROM `game` WHERE `email` = '".$_POST['email']."'") or exit(mysqli_error($connectionID));
if(mysqli_num_rows($select)) {
    exit('This email is already being used');
}

Stick that in abovethe insert query

将其粘贴在插入查询上方

回答by au_stan

First, to your question. The most simple is to use the header()function to redirect to a page.

首先,针对你的问题。最简单的就是使用header()函数重定向到一个页面。

if ( !$email) {
   header('Location: http://example.com/new_page.html' );
} else {
    // Continue with code
}

Secondly, there is a whole lot of issues going on in that code. For example:

其次,该代码中存在很多问题。例如:

  • Use PDO
  • parameterize your query
  • Your control statement should probably look like if(!empty($_POST['name'])) {
  • 使用 PDO
  • 参数化您的查询
  • 您的控制语句可能看起来像 if(!empty($_POST['name'])) {