Jump to content

Custom error message


mcwee93
Go to solution Solved by mcwee93,

Recommended Posts

Hey there, 

I have recently been drafted in by a friend to help create a web page that can be used externally alongside his website that he has recently created on bigcartel.com. The purpose of the page is to allow his shoppers to enter into a competition and have there details stored in a database so its easy enough for him to pick a winner. To ensure that each shopper could only enter once I made sure that the email input in the database field would be unique and hence forth return an error message which it does however I would like to use a custom error message. This is something that I have been unable to achieve though. 

The code that I have been trying to adapt and change is a piece of code that I got when I was at college so its been written for the purpose of getting a message to appear when an entry has been added successfully which works well but alongside that I want the error message to work too.

 

heres my code:

 

<?php 
$connection = mysql_connect("localhost","root",""); 
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
 
 
please help!! any help would be greatly appreciated 
 
$db_select = mysql_select_db("sourcedclothes",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
 
//The PHP isset function is used to check that the submit button //on the form has been
// clicked before any processing takes place. The return value //will be either true or false
 
if (isset($_POST['add_friend'])) { 
 
$sql="INSERT INTO competition (title, name, surname, phone, email) VALUES('$_POST[title]','$_POST[name]','$_POST[surname]','$_POST[phone]','$_POST')";
Link to comment
Share on other sites

Before you do the insert do a SELECT email FROM competition where email='$_POST' and if the number of rows returned is >0 then

 die ('e-mail address already in database'); // or whatever custom message you want

You also need to sanitize your data before using it in SQL. See http://php.net/manual/en/function.mysql-real-escape-string.php for more detail. If you don't you'll be hacked with an SQL injection attack.

Edited by davidannis
Link to comment
Share on other sites

so something along the lines of:

 

 

 

$stmt = $dbh->prepare("SELECT * FROM `contestant_drawing` WHERE `email`=:email")

$stmt->bindParam(':email',$email);

$stmt->execute();

if($stmt->rowCount()!=0){

exit('Email already exists');
}

 

 

 

 

if (isset($_POST['add_friend'])) { 
 
$sql="INSERT INTO competition (title, name, surname, phone, email) VALUES('$_POST[title]','$_POST[name]','$_POST[surname]','$_POST[phone]','$_POST')";
Link to comment
Share on other sites

You have the idea right. You can put the code to check for an existing e-mail inside

if (isset($_POST['add_friend'])) { 

as cyberroot said use one method to access the database, don't mix and match like you did in your example.

yeah i might look into that in the future thanks. how would i structure it if i were to put it into my 

if (isset($_POST['add_friend'])) {

 

as i said i'm still sort of new to this and its easy enough to take pieces of code that do things and input it in to my site but when i need to change or adapt it its all just going over my head.

Link to comment
Share on other sites

OK, something like this:

if (isset($_POST['add_friend'])) { 

// don't bother checking for a duplicate unless $_POST['add_friend'] is set
//meaning put code in here

//The next line sanitizes the email. If you don't do this and I put "david@david.com ; TRUNCATE competition" in the form e-mail field then I just erased your table. YOu need to sanitize every piece of data you run through mysql.
$email=mysql_real_escape_string($_POST['email']); 
$sql="SELECT email FROM competition WHERE email='$email'";
$result=mysql_query($sql,$connection);
if (mysql_num_rows($result)>0){
  die ('oops, that e-mail is in our database already');
}else{

 
$sql="INSERT INTO competition (title, name, surname, phone, email) VALUES('$_POST[title]','$_POST[name]','$_POST[surname]','$_POST[phone]','$_POST[email]')";
}
 
if (!mysql_query($sql,$connection));
  {
  die('Your details have been added to the system' . mysql_error());
  }
 
mysql_close($connection);
}
?>

I took a quick stab at illustrating what i meant. I did not change your code

Edited by davidannis
Link to comment
Share on other sites

Unless you're planning to use the POST variables for something other than the query, you could reassign the escaped value to the same variable. Otherwise, PHP needs to maintain two variables. Also, you need to escape all of the POST variables before running the queries.

<?php
//PREPARE POST DATA FOR QUERY
$_POST['title'] = mysql_real_escape_string($_POST['title']);
$_POST['name']  = mysql_real_escape_string($_POST['name']);
$_POST['email'] = mysql_real_escape_string($_POST['email']);
//... escape the rest here
?>

Note that the filter_var() function can be used to validate the email address. Example 1 in the link below shows how to check email addresses:

http://php.net/manual/en/function.filter-var.php

Link to comment
Share on other sites

  • Solution

OK, something like this:

if (isset($_POST['add_friend'])) { 

// don't bother checking for a duplicate unless $_POST['add_friend'] is set
//meaning put code in here

//The next line sanitizes the email. If you don't do this and I put "david@david.com ; TRUNCATE competition" in the form e-mail field then I just erased your table. YOu need to sanitize every piece of data you run through mysql.
$email=mysql_real_escape_string($_POST['email']); 
$sql="SELECT email FROM competition WHERE email='$email'";
$result=mysql_query($sql,$connection);
if (mysql_num_rows($result)>0){
  die ('oops, that e-mail is in our database already');
}else{

 
$sql="INSERT INTO competition (title, name, surname, phone, email) VALUES('$_POST[title]','$_POST[name]','$_POST[surname]','$_POST[phone]','$_POST[email]')";
}
 
if (!mysql_query($sql,$connection));
  {
  die('Your details have been added to the system' . mysql_error());
  }
 
mysql_close($connection);
}
?>
I took a quick stab at illustrating what i meant. I did not change your code

 

That piece of code worked perfectly thanks for all of your help!!

Edited by mcwee93
Link to comment
Share on other sites

@mcwee93 - Just because the code works, doesn't mean to say you should use it. CyberRobot made a good point about santizing your data.

 

I myself, had a little time so I had a go at re-creating what you require the way I would do it.

 

 

<?PHP

  if($_SERVER['REQUEST_METHOD'] == 'POST') {
 
    //### Connection variables
    $DBUser = 'root';
    $DBPass = '';
    $DBHost = '127.0.0.1';
    $DBName = 'test';

    //### Connect to database
    $mysqli = mysqli_connect($DBHost, $DBUser, $DBPass, $DBName) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
 
    //### Sanitize varaibles
    $_POST['title']   = isset($_POST['title']) ? strtolower(trim($_POST['title'])) : FALSE ;
    $_POST['name']    = isset($_POST['name']) ? strtolower(trim($_POST['name'])) : FALSE ;
    $_POST['surname'] = isset($_POST['surname']) ? strtolower(trim($_POST['surname'])) : FALSE ;
    $_POST['phone']   = isset($_POST['phone']) ? strtolower(trim($_POST['phone'])) : FALSE ;
    $_POST['email']   = isset($_POST['email']) ? strtolower(trim($_POST['email'])) : FALSE ;
    
    //### Check over the incoming data
    //### Check title
    if(empty($_POST['title'])) {
      $errors[] = 'You must enter your salutation.';
    }
    
    //### Check name
    if(empty($_POST['name'])) {
      $errors[] = 'You must enter your name.';
    }
    
    //### Check surname
    if(empty($_POST['surname'])) {
      $errors[] = 'You must enter your surname.';
    }
    
    //### Check phone
    if(empty($_POST['phone'])) {
      $errors[] = 'You must enter your phone number.';
    }
    
    //### Check email
    if(empty($_POST['email'])) {
      $errors[] = 'You must enter your e-mail address.';
    } else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
      $errors[] = 'You have entered an invalid e-mail address.';
    } else {
    
      //### Escape email
      $_POST['email'] = mysqli_real_escape_string($mysqli, $_POST['email']);
    
      //### Check to see if e-mail address if already in use
      $checkEmailQuery = "SELECT `email` FROM `competition` WHERE `email` = '{$_POST['email']}'";
      $checkEmail      = mysqli_query($mysqli, $checkEmailQuery);
      
      //### Check for mysqli error
      if(mysqli_error($mysqli)) {
        $processError = 'An error occured processing your request, please try again.';
      } else if(mysqli_num_rows($checkEmail)) {
        $errors[] = 'The e-mail address you have entered it already in use.';
      }    
    }
    
    //### Check to see if there are any process errors
    if(isset($processError)) {
      echo $processError.'<br>';
      
    //### Check to see if there are any data errors
    } else if(isset($errors)) {
      echo 'One or more errors occured processing your data: <br>';
      foreach($errors AS $error) {
        echo $error.'<br>';
      }
      
    //### No errors, proceed with processing request
    } else {
    
      //### Escape varaibles
      $_POST['title']   = mysqli_real_escape_string($mysqli, $_POST['title']);
      $_POST['name']    = mysqli_real_escape_string($mysqli, $_POST['name']);
      $_POST['surname'] = mysqli_real_escape_string($mysqli, $_POST['surname']);
      $_POST['phone']   = mysqli_real_escape_string($mysqli, $_POST['phone']);
    
      //### Insert record in to database table
      $insertRecordQuery = "INSERT INTO `competition` (`title`, `name`, `surname`, `phone`, `email`) VALUES ('{$_POST['title']}', '{$_POST['name']}', '{$_POST['surname']}', '{$_POST['phone']}', '{$_POST['email']}')";
      $insertRecord      = mysqli_query($mysqli, $insertRecordQuery);
      
      //### Check for mysqli error
      if(mysqli_error($mysqli)) {
        echo 'An error occured saving your data, please try again. <br>';        
      } else {        
        //### Redirect, to prevent form submission from refreshing
        header('Location: ?success=true');
        exit;        
      }    
    }  
  }
 
?>

<form method="POST" action="?">
<?PHP
  if(isset($_GET['success'])) {
    echo 'Thanks you! Your details have been successfully added to the system. <br>';
  }
?>
  Title: <input type="text" name="title"> <br>
  Name: <input type="text" name="name"> <br>
  Surname: <input type="text" name="surname"> <br>
  Contact Number: <input type="text" name="phone"> <br>
  E-mail Address: <input type="text" name="email"> <br>
  <input type="submit" value="Submit">
</form>
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.