im working on a part of program where i need to send null to my database if the textbox is empty here is what i have so far
<?php
//so if not connected to database it displays an error message instead of a php error recommend having on 1 in development mode - for warnings and error
ini_set( "display_errors", 0);
if(!$_POST) exit;
$con = mysql_connect("localhost","imstillr","password");
mysql_select_db("imstillr_crm", $con);
$company = protect($_POST['company']); //required
$primarycontact = protect($_POST['primarycontact']); //required
$primaryemail = protect($_POST['primaryemail']); //required
$preferphone = protect($_POST['preferphone']); //required
$secondarycontact = protect($_POST['secondarycontact']);
$secondaryemail = protect($_POST['secondaryemail']);
$optionalphone = protect($_POST['optionalphone']);
$department = protect($_POST['department']);
$website = protect($_POST['website']); //required*/
//database info
mysql_query("SELECT companyname FROM customerinfo WHERE companyname='" .$company. "'");
if (!$con)
{
//checks if database connection string is correct
echo '<div class="error_message">Attention! no database connection.</div>';
exit();
} else if(mysql_affected_rows() == 1) {
echo '<div class="error_message">Attention! This company already exists.</div>';
exit();
} else if(trim($company) == '') {
echo '<div class="error_message">Attention! You must enter your company name.</div>';
exit();
} else if(trim($primarycontact) == '') {
echo '<div class="error_message">Attention! You must enter a contact name.</div>';
exit();
} else if(trim($primaryemail) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(!isEmail($primaryemail)) {
echo '<div class="error_message">Attention! You have to enter an invalid e-mail address, try again.</div>';
exit();
} else if(trim($department) == '') {
echo '<div class="error_message">Attention! Please enter a department.</div>';
exit();
} else if(trim($preferphone) == '') {
echo '<div class="error_message">Attention! Please enter a preferred phone number.</div>';
exit();
} else if(!isPhone($preferphone)) {
echo '<div class="error_message">Attention! Please enter the right format for phone.</div>';
exit();
} else if(trim($website) == '') {
echo '<div class="error_message">Attention! Please enter a website name.</div>';
exit();
}
if($error == '') {
$secondarycontact = NULL;
$secondaryemail = 'random text';
$optionalphone = 'random text';
$address = "example#yahoo.com";
$clientaddress = $primaryemail;
//admin subject
$e_subject = $primarycontact .' has successfully been registered in the database';
//client subject
$c_subject = 'You have successfully been registered in the database';
/* another way of doing admin client email as array
$admin_email = array(
'e_body' => '$primarycontact has been registered in department '$department' \r\n\n',
'e_content' => 'You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n';
'e_reply' => 'You can contact $primarycontact via email, $primaryemail';
);*/
//admin email
$e_body = "$primarycontact has been registered in department '$department' \r\n\n";
//$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n";
$e_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
//$e_content = "\"anything can be displayed here such as all the customers entered info\"\r\n\n";
$e_reply = "You can contact $primarycontact via email, $primaryemail ";
//client email
$c_body = "You has been registered in department '$department' \r\n\n";
$c_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
$c_reply = "For anymore information feel free to contact the administrator vis email, $address";
//admin msg
$msg = $e_body . $e_content . $e_reply;
//client msg
$cmsg = $c_body . $c_content . $c_reply;
//inserts information
mysql_query("INSERT INTO `imstillr_crm`.`customerinfo` (`id`, `companyname`, `primarycontact`, `primaryemail`, `prefphone`, `secondarycontact`, `secondaryemail`, `optionalphone`, `department`, `website`) VALUES (NULL, '".$company."', '".$primarycontact."', '".$primaryemail."', '".$preferphone."', '".$secondarycontact."', '".$secondaryemail."', '".$optionalphone."', '".$department."', '".$website."')");
if(mail($address, $e_subject, $msg, "From: $primaryemail\r\nReply-To: $primaryemail\r\nReturn-Path: $primaryemail\r\n")) {
//if mail was sent to admin then send to person who signed up
mail($primaryemail, $c_subject, $cmsg, "From: $address\r\nReply-To: $address\r\nReturn-Path: $address\r\n");
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo $secondarycontact. '<br />';
echo $secondaryemail. '<br />';
echo $optionalphone. '<br />';
//echo "<h1>User $primarycontact Successfully added onto '$department'.</h1>";
echo "<p>Thank you <strong>$primarycontact</strong>, your registration info has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
//all functions go here
//protects database from SQL injection
function protect($value) {
if(get_magic_quotes_gpc()){
return mysql_real_escape_string(stripslashes($value));
}else{
return mysql_real_escape_string($value);
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
function isPhone($number) {
return(preg_match("/^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$/",$number));
}
?>
optionalphone,secondaryemail and secondarycontact are the only values that can be null
This will not work:
$foo = null;
mysql_query("INSERT INTO ... VALUES (".$foo.")");
This will:
mysql_query("INSERT INTO ... VALUES (NULL)");
So you might want to do it this way:
function quoted_string_or_null($var) {
return $var === null ? 'NULL' : "'".$var."'";
}
$foo = null;
mysql_query("INSERT INTO ... VALUES (".quoted_string_or_null($foo).")");
However, there is another problem: there is no way you will be getting real null values from your protect function or from $_POST. So you have to decide if an empty string is a legal value, or if empty strings should be converted to null. It's probably the latter, so you can make a small change and work with this:
function quoted_string_or_null($var) {
return ($var === null || $var === '') ? 'NULL' : "'".$var."'";
}
Rather than manually quoting the strings, use something to do this for you. See http://php.net/manual/en/function.mysql-real-escape-string.php
In the comments is a function written for your issue:
<?php
function db_escape($values, $quotes = true) {
if (is_array($values)) {
foreach ($values as $key => $value) {
$values[$key] = db_escape($value, $quotes);
}
}
else if ($values === null) {
$values = 'NULL';
}
else if (is_bool($values)) {
$values = $values ? 1 : 0;
}
else if (!is_numeric($values)) {
$values = mysql_real_escape_string($values);
if ($quotes) {
$values = '"' . $values . '"';
}
}
return $values;
}
?>
Once you have escaped each value, pass it without any extra quotes to the insert command.
Related
I have created a PHP script that allows users on my site to sign up for our newsletter by entering their email and pressing the submit button. Then, it will give the user a notification to say that they have successfully signed up for our newsletter, and I will get an email. However, when you load the page (https://papaya-os.000webhostapp.com/) it sends me the email saying that somebody signed up, but the submit button was never pressed, and it doesn't show a success notification. On top of that, when you try to use the form correctly it doesn't work. Here is my PHP:
if($_POST["submit"]) {
if(!$_POST["email"]) {
$error = 'Please Enter Your Email';
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' .$error. '</strong></div>';
}
} else {
if(mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: ".$_POST['email'])) {
$result='<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
?>
I tried running the PHP on the top, and then the bottom of my HTML code, but neither worked. Any help is appreciated. Thanks!
you have mistake in parenthesis
if($_POST["submit"]) {
if(!$_POST["email"]) {
$error = 'Please Enter Your Email';
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' .$error. '</strong></div>';
} else {
if(mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: ".$_POST['email'])) {
$result='<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}
<?
//Here you should be checking if submit is set, or `empty()` is my preferred function. You could also use `isset()` but you would want to negate that, so it would be `!isset()`.
if(empty($_POST["submit"])) {
//If email is empty, set $error
if(empty($_POST["email"])) {
$error = 'Please Enter Your Email';
}
//if $error is not empty, set $result
if (!empty($error)) {
$result = '<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' . $error . '</strong></div>';
}
//if $_POST["submit"] IS set, send email.
} else {
//if $_POST['submit'] is NOT empty, and IS set, send email.
if(isset($_POST['submit'])) {
if (mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: " . $_POST['email'])) {
$result = '<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}
?>
Try this code, and I added comments to explain what was happening.
I personally would have wrote it to be more dynamic with the error code.
Here is how I would have personally wrote the code. I'm not claiming this is better or worse, just how I would have done it. :)
<?php
//if submit is empty there was an issue
if (empty($_POST['submit'])) {
//create an empty array to store errors
$errors = array();
//loop through each _POST element to see what you are missing. If any value is empty or not set, it will be added to the errors.
foreach ($_POST as $key => $value) {
//skip key submit because we don't want that to appear in the errors, you could also add more you want to skip here.
if ($key == "submit")
continue;
//If value is empty/not set, add it to the error array.
if (empty($value)) {
array_push($errors, "Please provide " . ((in_array($key[0], $vocals)) ? "an" : "a") . " {$key}");
}
}
//check if $errors has any contents
if (!empty($errors)) {
//create $results filled with the dynamic errors from above. If there is only 1 error, properly format the sentence.
$result = '<div class="alert alert-danger"><strong>There '.((count($errors)==1)? "was an error" : "were errors" ).' while submitting the form: ';
foreach ($errors as $key => $value) {
$result .= "{$value}";
if ($key != count($errors) - 1) {
$result .= ", ";
}
}
$result .= '</strong></div>';
}
} else {
//if if $_POST['submit'] is not empty and IS set, send email.
if(isset($_POST['submit'])) {
$to = "test#email.com";
$subject = "Newsletter Sign Up";
$message = "Email: {$_POST['email]}";
if (mail($to, $subject, $message)) {
$result = '<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}
?>
You're structure is wrong so it's always hitting that block. You have the closing bracket for your if in the wrong place. Try this.
<?php
if($_POST["submit"]) {
if(!$_POST["email"]) {
$error = 'Please Enter Your Email';
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' .$error. '</strong></div>';
} else {
if(mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: ".$_POST['email'])) {
$result='<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}
?>
So as the title states I receive blank emails from my contact form. The php code is below. I've checked the value of $msg and it appears correctly, I've also googled a ton and I can't find anything standard cause that apply to me.
<?php
main();
function main() {
$posted = setVariables();
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);
}
function setVariables() {
$name;
if (isset($_POST['name'])){
$name=$_POST['name'];
if ($name == null) {
$name = "ERROR - name is null";
}
}
$email;
if (isset($_POST['email'])){
$email=$_POST['email'];
if ($email == null) {
$email = "ERROR - email is null";
}
}
$enquiry;
if (isset($_POST['enquiry'])){
$enquiry=$_POST['enquiry'];
if ($enquiry == null) {
$enquiry = "ERROR - enquiry is null";
}
}
$message;
if (isset($_POST['message'])){
$message=$_POST['message'];
if ($message == null) {
$message = "ERROR - message is null";
}
}
$posted = array($name,$email,$enquiry,$message);
return $posted;
}
function setMessage($posted) {
$msg = "Name: " . $posted[0] . "\r\nEmail: " . $posted[1] . "\r\nEnquiry: " . $posted[2] . "\r\nMessage: " . $posted[3];
$msg = wordwrap($msg,70);
$msg = Trim(stripslashes($_POST['Message']));
return $msg;
}
function sendMail($msg) {
$result = mail("social#georgeappleton.co.uk","Contact From Portfolio",$msg, "From: <info#yourdomain.co.uk>");
return $result;
}
function userFeedback($result) {
if ($result == false) {
echo "Message failed to send, please inform me through my email address. social#georgeappleton.co.uk";
} else {
echo "Message Sent!<br/><br/>Returning you to <a href='http://www.georgeappleton.co.uk'>georgeappleton.co.uk</a> in 5 seconds";
}
echo "<script>setTimeout(function() {window.location = 'http://www.georgeappleton.co.uk';},5000);</script>";
}
?>
Thanks guys, appreciate it a lot
-Shardj
Get rid of this line:
$msg = Trim(stripslashes($_POST['Message']));
It's overwriting $msg with the contents of a nonexistent parameter. It already contains the message text, which was in $posted[3].
It's your variable scope. $name withing setVariables()
$name=$_POST['name'];
if (strlen($name) < 1) {$name = "ERROR - name is null";}
$email=$_POST['email'];
if (strlen($email) < 1) {$email = "ERROR - email is null";}
$enquiry=$_POST['enquiry'];
if (strlen($enquiry) < 1) {$enquiry = "ERROR - enquiry is null";}
$posted = array($name,$email,$enquiry,$message);
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);
Js fiddle to have a look into form:http://jsfiddle.net/aBp34/
The form working finely ,it's just that I'm unable to insert any data into the database.
Surprisingly there's no error generated!
*ERROR:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''name','nric','hp','gender','occupation','ins_orga','events','size')VALUES(kalai' at line 1*
Below is the mysqli commands in php:
Any help would be appreciated :)
<?php
if(isset($_POST['submitted']))
{
if(empty($_POST['name']))
{
$name=NULL;
echo'Please fill up your name!'.'</br>';
}
else
//to check name(char only)
if(!empty($_POST['name']))
{
$name=$_POST['name'];
$pattern='/([[:alpha:]]|[[:space:]])/';
if(!preg_match($pattern, $name))//slighly silly but it echo only if preg_match mismatch
{
echo 'Please key in a valid name!'.'</br>';
}
}
// to check NRIC(only numbers and size=12)
if(empty($_POST['nric']))
{
$nric=NULL;
echo'Please key in your NRIC!'.'</br>';
}
else
if(!empty($_POST['nric']))
{
$nric=$_POST['nric'];
$pattern='/[0-9]{12}/';
if(!preg_match($pattern, $nric))
{
echo 'Please key in a valid NRIC number!'.'</br>';
}
}
//to check h/p number
if(empty($_POST['hp']))
{
$hp=NULL;
echo'Please key in your H/P Number!'.'</br>';
}
else
if(!empty($_POST['hp']))
{
$hp=$_POST['hp'];
$pattern='/(\\d{10})/';
if(!preg_match($pattern, $hp))
{
echo 'Please key in a valid Mobile number!'.'</br>';
}
}
//to check email
if(empty($_POST['email']))
{
$email=NULL;
echo'Please key in your email id!';
}
else
if(!empty($_POST['email']))
{
$hp=$_POST['email'];
$pattern='/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!"?(?>\\\[ -~]|[^"]){65,}"?#)(?>([!#-\'*+\/-9=?^-~-]+)(?>\.(?1))*|"(?>[ !#-\[\]-~]|\\\[ -~])*")#(?!.*[^.]{64,})(?>([a-z\d](?>[a-z\d-]*[a-z\d])?)(?>\.(?2)){0,126}|\[(?:(?>IPv6:(?>([a-f\d]{1,4})(?>:(?3)){7}|(?!(?:.*[a-f\d][:\]]){8,})((?3)(?>:(?3)){0,6})?::(?4)?))|(?>(?>IPv6:(?>(?3)(?>:(?3)){5}:|(?!(?:.*[a-f\d]:){6,})(?5)?::(?>((?3)(?>:(?3)){0,4}):)?))?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?6)){3}))\])$/iD';
if(!preg_match($pattern, $hp))
{
echo 'Please key in a valid email id!'.'</br>';
}
}
//to check gender
if(!isset($_POST['gender']))
{
$gender=NULL;
echo"Kindly select your gender!".'</br>';
}
else
{
$gender=$_POST['gender'];
}
//to check occupation
if(!isset($_POST['occupation']))
{
$occupation=NULL;
echo"Kindly select your occupation!".'</br>';
}
else
{
$occupation=$_POST['occupation'];
if(empty($_POST['ins_orga']))
{
echo'Please name your institution or organization!';
}
else
{
$ins_orga=$_POST['ins_orga'];
}
}
//to check events
if(!empty($_POST['events']))
{
$events = $_POST['events'];
}
if(!isset($events))
{
echo("<p>You didn't select any events!</p>\n").'</br>';
}
else
{
$nevents = count($events);
echo"You selected ".$nevents ."events: ".'</br>';
for($i=0; $i < $nevents; $i++)
{
echo($events[$i] . " ");
}
}
if(empty($_POST['size']))
{
echo"please select your size".'</br>';
}
else
{
$size=$_POST['size'];
echo $size;
}
if(isset($_POST['area']))
{
$area=$_POST['area'];
}
if(isset($_POST['captain_code']))
{
$captain_code=$_POST['captain_code'];
}
if(isset($_POST['address']))
{
$address=$_POST['address'];
}
if(isset($_POST['s1']))
{
$s1=$_POST['s1'];
}
// check all
if('$name'&&'$nric'&&'$hp'&&'$email'&&'$gender'&&'$occupation'&&'$events'&&'$size')
{
echo "you have successfully registered! Your code is: ";
// set uniqid
$order_id = uniqid(rand(10,1000),false);
$order_id = substr($order_id,rand(0,strlen($order_id) - 4),4);
echo hexdec($order_id);
$mysqli=new mysqli('localhost','root','','volunteer-registration');
if(mysqli_connect_errno())
{
echo 'Connection failed', mysql_connect_error();
exit();
}
$insert="INSERT INTO volunteer_registration(name,nric,hp,email_id,address,gender,occupation,ins_orga,events,size,area,s1,captain_code)VALUES($name,$nric,$hp,$email,$address,$gender,$occupation,$ins_orga,$events,$size,$area,$s1,$captain_code)";
$query= mysqli_query($mysqli, $insert)or die(mysqli_error($mysqli));
}
}
?>
With the issues pointed by others following code snippet
$row=$result->fetch_fields();
foreach($result as $val)
{
///
}
I think it should be
$row=$result->fetch_fields();
foreach($row as $val)
{
///
}
First issue I see:
if('$name'&&'$nric'&&'$hp'&&'$email'&&'$gender'&&'$occupation'&&'$events'&&'$size')
should be
if (isset($name, $nric, $hp, $email, $gender, $occupation, $events, $size))
The way you are doing it now you are just seeing if the string literal '$name' is truthy - which it always will be, since you aren't checking the variable $name.
Next issue is that you never do an insert into the database, just a select.
Edit: with your insert, you have
$insert="INSERT INTO volunteer_registration(...)VALUES($name,$nric, ... , $captain_code)
You need to put quotes around the values:
$insert="INSERT INTO volunteer_registration(...)VALUES('$name','$nric', ... ,'$captain_code')
I just fix your validation, and for the sql code is up to you
maybe you can try to make it more simple...
<?php
if (isset($_POST['submitted'])) {
$msg = "";
$name = $_POST['name'];
$pattern='/([[:alpha:]]|[[:space:]])/';
if (empty($name)) {
$msg .= "<li>Please fill up your name!</li>";
}
if (!preg_match($pattern, $name)) {
$msg .= "<li>Please key in a valid name!</li>";
}
if (empty($_POST['nric'])) {
$msg .= "<li>Please key in your NRIC!</li>";
}
if (!is_numeric($_POST['nric'])) {
$msg .= "<li>Please key in a valid NRIC number!</li>";
}
if (empty($_POST['hp'])) {
$msg .= "<li>Please key in your H/P Number!</li>";
}
if (!is_numeric($_POST['nric']) && $_POST['nric'] < 10) {
$msg .= "<li>Please key in a valid Mobile number!</li>";
}
if (empty($_POST['email'])) {
$msg .= "<li>Please key in your email id!</li>";
}
if ((!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$_POST['email']))) {
$msg .= "<li>Please key in a valid email id!</li>";
}
if (empty($_POST['gender'])) {
$msg .= "<li>Kindly select your gender!</li>";
}
if (empty($_POST['occupation'])) {
$msg .= "<li>Kindly select your occupation!</li>";
}else{
$occupation=$_POST['occupation'];
if(empty($_POST['ins_orga'])) {
$msg .= "<li>Please name your institution or organization!</li>";
}else{
$ins_orga=$_POST['ins_orga'];
}
}
if (empty($_POST['events'])) {
$msg .= "<li>You didn't select any events!</li>";
}
else{
$nevents = count($events);
# ...
}
if(empty($_POST['size'])) {
$msg .= "<li>please select your size!</li>";
}
if ($msg=="") {
$order_id = uniqid(rand(10,1000),false);
$order_id = substr($order_id,rand(0,strlen($order_id) - 4),4);
$code = hexdec($order_id);
$msg .= "you have successfully registered! Your code is: ".$code."";
# Your code SQL...
# ......
#......
}
}
?>
<?php echo $msg; ?>
This is my registration code.
Once I enter the fields in the form it shows me registration successful but adds blank data in my database table. It adds number 0 in my mobileno column.
Please help me here asap
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number ';//add to array "error"
} else {
$name = $_POST['mobileno'];//else assign it a variable
}
if (empty($_POST['fname'])) {//if no name has been supplied
$error[] = 'Please Enter a First name ';//add to array "error"
} else {
$name = $_POST['fname'];//else assign it a variable
}
if (empty($_POST['lname'])) {//if no name has been supplied
$error[] = 'Please Enter a Last name ';//add to array "error"
} else {
$name = $_POST['lname'];//else assign it a variable
}
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA- Z0-9\._-]+)+$/", $_POST['email'])) {
//regular expression for email validation
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwd1'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwd1'];
}
if (empty($_POST['passwd2'])) {
$error[] = 'Please Verify Your Password ';
} else {
$Password = $_POST['passwd2'];
}
if (empty($error)) //send to Database if there's no error '
{ //If everything's OK...
// Make sure the mobile no is available:
$query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobileno'";
$result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno);
if (!$result_verify_mobileno)
{//if the Query Failed ,similar to if($result_verify_mobileno==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_mobileno) == 0) { // IF no previous user is using this number .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO userdtls (`mobileno`, `pass`, `fname`, `lname`, `email`, `activation`) VALUES ( '$mobileno', '$passwd1', '$fname', '$lname', '$email', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From: rahul19dj#gmail.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The mobile number is not available.
echo '<div class="errormsgbox" >That mobile number has already been registered.</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
You're assigning all of your variables, except $email to $name overwriting each one in succession. This is definitely going to cause strange results which are dependant on the data types of each column in your dataase. If mobileno is set to be an int has a default value of 0 a string or empty value will result in you seeing 0 in your dataase.
<?php
if (isset($_POST['ign'], $_POST['email'])) {
if($_POST['ign'] && $_POST['email']){
}
else {
echo ("Please enter all of the values!");
}
}
else {
echo ("Error in form data!");
}
if((FILTER_VALIDATE_EMAIL($_POST['email'] == TRUE))) {
$email = $_POST['email'];
echo ("Thanks, " . htmlentities($_POST['ign']) . ", you will recieve an email when the site is complete!");
}
else {
echo "Failure!";
}
// insert email and ign into database
?>
Is this going to work correctly? First time doing something completely from scratch lol!
OK! I have changed it. What about this? Should I also do the empty thing?
<?php
if (!isset($_POST['ign'], $_POST['email'])) {
if($_POST['ign'] && $_POST['email']){
echo "Please fill out all of the fields!";
die;
}
if(var_filter($_POST['email'], FILTER_VALIDATE_EMAIL))
$email = $_POST['email'];
echo ("Thanks, " . htmlentities($_POST['ign']) . ", you will recieve an email when the site is complete!");
}
else {
echo "Your email was invalid!";
}
// insert email and ign into database
?>
Use built in functions, don't re-invent the wheel:
if(filter_var($mail, FILTER_VALIDATE_EMAIL)){
echo "Mail is valid!";
}
WHY IS YOUR FUNCTION NAME ALL CAPS?
...and do you see the difference between this...
if(func($_POST['email'] == TRUE)){
and this..
if(func($_POST['email']) == TRUE){
?
There are lots of mistakes there. Here's what you should be doing:
// First check if both fields are present. Usually there is no point in doing this
// because the next check will also catch this case, but you had it so I put it in too.
if (!isset($_POST['ign'], $_POST['email'])) {
echo ("Error in form data!");
die; // or something else
}
// Then check if both values are non-"empty" (you might want to look at the docs for
// an explanation of what this means exactly).
if (empty($_POST['ign']) || empty($_POST['email'])) {
echo ("Please enter all of the values!");
die; // or something else
}
// Finally, validate the email. DO NOT COMPARE WITH true!
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "Failure!";
die; // etc
}
echo ("Thanks, " . htmlentities($_POST['ign']) . ", blah blah!");