Hi, this is my form wherein I can validate if the e-mail is valid or not, the phone number is less 7 or less, and if the form is complete. What I want now is, to validate of the Phone number already exists in my mysql database or not. Here's my code: <?php $errors=0; $error="<b>The following errors occured while processing your form input.</b><br /><br />"; $Name = $_POST['Name']; $Email = $_POST['Email']; $CellNumberPre = $_POST['CellNumberPre']; $CellNumber = $_POST['CellNumber']; $AlertOn = $_POST['AlertOn']; if($Name=="" || $Email=="" || $CellNumberPre=="" || $CellNumber=="" || $AlertOn=="" ){ $errors=1; $error.="<p>You did not enter one or more of the required fields. Please go <a href=\"javascript:history.go(-1)\"><b>back</b></a> and try again.</p>"; } if(!preg_match("/^\d+$/",$CellNumber)){ $errors=1; $error.="<p>Only numbers are accepted in the cell number field. Please go <a href=\"javascript:history.go(-1)\"><b>back</b></a> and try again.</p>"; } if (strlen($CellNumber) < 7){ $errors=1; $error.="<p>Your cellphone number is not valid. Please go <a href=\"javascript:history.go(-1)\"><b>back</b></a> and try again.</p>"; } if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."@"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$Email)){ $error.="<p>Invalid email address entered. Please go <a href=\"javascript:history.go(-1)\"><b>back</b></a> and try again.</p>"; $errors=1; } if($errors==1) echo $error; else{ $link = mysql_connect("localhost","username","password"); mysql_select_db("smsdatabase",$link); $query="insert into sms_subscribers (name,email,cnp,cn,alerton) values ('".$Name."','".$Email."','".$CellNumberPre."','".$CellNumber."','".$AlertOn."')"; mysql_query($query); ?> PHP: Where will I insert the line of code wherein I'll validate of the $cellnumber already exists, and how can I do it? Need help I'm just a php noob That's all I hope someone can give me a simple to understand answer
$query='select 1 from sms_subscribers where cn='.mysql_real_escape_string($CEllNumber); $result=mysql_query($query,$link); if (mysql_num_rows($result)>0) { //number exists; } PHP:
I guess that if you make the "cnp" column on your database setup UNIQUE; MySQL will not execute your query if you are trying to INSERT a value on "cnp" that already exists. BTW; you really should read some articles about the mysql_real_escape_string() before you're site get hacked by a a SQL injection !!!
before if($errors==1) echo $error; PHP: add $query='select 1 from sms_subscribers where cn='.mysql_real_escape_string($CEllNumber);$result=mysql_query($query,$link); if (mysql_num_rows($result)>0) { //number exists; $error.="<p>Cell phone number entered already exists. Please go <a href=\"javascript:history.go(-1)\"><b>back</b></a> and try again.</p>"; $errors=1; } PHP: you would also need to move $link = mysql_connect("localhost","username","password"); mysql_select_db("smsdatabase",$link); PHP: above this added query, else it has nothing to connect to the DB with.