0

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

  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();

  }

?>
Amaan Iqbal
  • 761
  • 2
  • 9
  • 25
Erwin van Ekeren
  • 710
  • 4
  • 13
  • 36
  • 2
    Please don't use `mysql_*` functions to write new code. See the [red box](http://uk.php.net/manual/en/function.mysql-connect.php)? Instead you should learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) and use either [PDO](http://www.php.net/pdo) or [MySQLi](http://www.php.net/mysqli). If you can't decide which, [this article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you. Also see http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – Marijke Luttekes Feb 26 '14 at 15:28

2 Answers2

5
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 above the insert query

Magictallguy
  • 622
  • 4
  • 16
0

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

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'])) {
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
au_stan
  • 4,011
  • 2
  • 19
  • 24
  • 1
    use @magictallguy code. i didn't write that as i thought you were just looking for a redirect. – au_stan Feb 26 '14 at 15:35