0

How do I add a email validation to this pdo script. the user enters their email address in 'textfield'. simply if the email address entered is not in the database I want it to redirect to fail.html

<?php

$host=""; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name=""; // Database name 
$tbl_name="orders"; // Table name  
$email = $_POST['textfield'];


        $db = new PDO('mysql:host='.$host.
                          ';dbname='.$db_name.
                          ';charset=UTF-8',
                    $username, $password);
        $stmt = $db->prepare('SELECT * FROM `orders` WHERE `email`=:email LIMIT 1');
        $stmt->bindValue(':email', $email, PDO::PARAM_STR);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        echo "The is: ".$result['name'].", and mail is: ".$result['email']." . Status: ".$result['status'];


  ?>
Luke Ham
  • 17
  • 1
  • 5

1 Answers1

2
if($stmt->rowCount()>0)
{
    echo "The result is: ".$result['name'].", and mail is: ".$result['email']." . Status: ".$result['status'];
}
else
{
    echo "Email not found in the database!";
}

Instead of echoing an error message, you can redirect to another page (only if nothing has already been sent to the browser):

header('Location: fail.html');

Or you can include the file to display it in the current page:

require 'fail.html';

Or you can use it in a form input field:

echo '<input name="login" type="text" value="' . $result['name'] . '>';

The field has its name attribute set to login, so you will be able to refer to it once the form is submitted.

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
  • thanks works. If i want to display using textfield by ' rather than echo "The result is: ".$result['name']....... how would I go about changing the validation? – Luke Ham Apr 30 '13 at 16:35
  • not sure why but when i replace echo "Email not found in the database!"; with header('Location: fail.html'); it does not redirect if email is wrong – Luke Ham Apr 30 '13 at 16:50
  • I wrote in my answer **(only if nothing has already been sent to the browser)**. Read [Headers already sent](http://stackoverflow.com/q/8028957/1409082) to learn how to fix the failing header redirect. – Jocelyn Apr 30 '13 at 16:53
  • ok got it now. the textfield where I want to display the results is in the body of the page. Can I echo the results in the body rather than in the PHP script. – Luke Ham Apr 30 '13 at 17:19