mcwee93 Posted September 16, 2013 Share Posted September 16, 2013 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')"; } if (!mysql_query($sql,$connection)); { die('Your details have been added to the system' . mysql_error()); } mysql_close($connection); ?> Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/ Share on other sites More sharing options...
davidannis Posted September 17, 2013 Share Posted September 17, 2013 (edited) 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 September 17, 2013 by davidannis Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449794 Share on other sites More sharing options...
mcwee93 Posted September 17, 2013 Author Share Posted September 17, 2013 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')"; } if (!mysql_query($sql,$connection)); { die('Your details have been added to the system' . mysql_error()); } mysql_close($connection); ?> im kinda new to the whole php thing can do the basics but not sure what you mean by sanatize my data? Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449847 Share on other sites More sharing options...
cyberRobot Posted September 17, 2013 Share Posted September 17, 2013 @mcwee93 - Which API are you using to connect with MySQL (MySQL, PDO, or MySQLi)? Side note: mysql_ functions have been depreciated. At some point in the near future, you'll need to look into the alternatives. More information can be found here: http://www.php.net/manual/en/mysqlinfo.api.choosing.php Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449849 Share on other sites More sharing options...
mcwee93 Posted September 17, 2013 Author Share Posted September 17, 2013 just using mysql just now cause thats what i was taught to use at college learning more about it though at uni this year Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449851 Share on other sites More sharing options...
davidannis Posted September 17, 2013 Share Posted September 17, 2013 just using mysql just now cause thats what i was taught to use at college learning more about it though at uni this year mysqli can be used almost exactly like mysql in terms of coding with only a few minor changes. If you are coding from scratch you may as well use it. Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449871 Share on other sites More sharing options...
davidannis Posted September 17, 2013 Share Posted September 17, 2013 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. Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449876 Share on other sites More sharing options...
mcwee93 Posted September 17, 2013 Author Share Posted September 17, 2013 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. Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449881 Share on other sites More sharing options...
davidannis Posted September 18, 2013 Share Posted September 18, 2013 (edited) 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 September 18, 2013 by davidannis Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449975 Share on other sites More sharing options...
davidannis Posted September 18, 2013 Share Posted September 18, 2013 yeah i might look into that in the future thanks. I believe that if you mix mysql access methods in the same script your programs won't work so choose PDO, mysql, or mysqli now and stick with it. Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1449976 Share on other sites More sharing options...
cyberRobot Posted September 18, 2013 Share Posted September 18, 2013 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 Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1450049 Share on other sites More sharing options...
Solution mcwee93 Posted September 18, 2013 Author Solution Share Posted September 18, 2013 (edited) 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 September 18, 2013 by mcwee93 Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1450068 Share on other sites More sharing options...
PaulRyan Posted September 18, 2013 Share Posted September 18, 2013 @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> Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1450093 Share on other sites More sharing options...
cyberRobot Posted September 18, 2013 Share Posted September 18, 2013 I have marked the topic as solved. If you need further assistance, please mark it as unsolved...or start a new thread. Quote Link to comment https://forums.phpfreaks.com/topic/282207-custom-error-message/#findComment-1450094 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.