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; ?>
Related
Below is the code that I have copied as I was following a tutorial and the affected code is line 150 where it is telling me this error: Fatal error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, mysqli given in C:\xampp\htdocs\shopping cart\shop_order.php:150 Stack trace: #0 C:\xampp\htdocs\shopping cart\shop_order.php(150): implode(Array, Object(mysqli)) #1 {main} thrown in C:\xampp\htdocs\shopping cart\shop_order.php on line 150
<?php
/* Program name: Shop_order.php
* Description: Processes order when it's been submitted.
*/
session_start();
include("dbinfo.inc");
if(!isset($_SESSION['order_number']))
{
echo "No order number found<br>\n
<a href='shop_products.php'>Continue shopping</a>";
exit();
}
if(#$_GET['from'] == "cart")
{
include("shop_form_shipinfo.inc");
exit();
}
elseif(isset($_POST['Summary']))
{
foreach($_POST as $field => $value)
{
if ($value == "")
{
$blanks[] = $field;
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if(isset($blanks))
{
$message = "The following fields are blank.
Please enter the required information: ";
foreach($blanks as $value)
{
$message .="$value, ";
}
extract($good_data);
include("shop_form_shipinfo.inc");
exit();
}
foreach($_POST as $field => $value)
{
if($field != "Summary")
{
if(preg_match("/name/i",$field))
{
if (!preg_match("/^[A-Za-z' -]{1,50}$/",$value))
{
$errors[] = "$value is not a valid name.";
}
}
if(preg_match("/street/i",$field)or
preg_match("/addr/i",$field) or
preg_match("/city/i",$field))
{
if(!preg_match("/^[A-Za-z0-9.,' -]{1,50}$/",$value))
{
$errors[] = "$value is not a valid address
or city.";
}
}
if(preg_match("/state/i",$field))
{
if(!preg_match("/[A-Za-z]/",$value))
{
$errors[] = "$value is not a valid state.";
}
}
if(preg_match("/email/i",$field))
{
if(!preg_match("/^.+#.+\\..+$/",$value))
{
$errors[]="$value is not a valid email address.";
}
}
if(preg_match("/zip/i",$field))
{
if(!preg_match("/^[0-9]{5,5}(\-[0-9]{4,4})?$/",
$value))
{
$errors[] = "$value is not a valid zipcode.";
}
}
if(preg_match("/phone/i",$field))
{
if(!preg_match("/^[0-9)(xX -]{7,20}$/",$value))
{
$errors[]="$value is not a valid phone number. ";
}
}
if(preg_match("/cc_number/",$field))
{
$value = trim($value);
$value = ereg_replace(' ','',$value);
$value = ereg_replace('-','',$value);
$_POST['cc_number'] = $value;
if($_POST['cc_type'] == "visa")
{
if(!preg_match("/^[4]{1,1}[0-9]{12,15}$/",$value))
{
$errors[]="$value is not a valid Visa number. ";
}
}
elseif($_POST['cc_type'] == "mc")
{
if(!preg_match("/^[5]{1,1}[0-9]{15,15}$/",$value))
{
$errors[] = "$value is not a valid
Mastercard number. ";
}
}
else
{
if(!preg_match("/^[3]{1,1}[0-9]{14,14}$/",$value))
{
$errors[] = "$value is not a valid
American Express number. ";
}
}
}
$$field = strip_tags(trim($value));
}
}
if(#is_array($errors))
{
$message = "";
foreach($errors as $value)
{
$message .= $value." Please try again<br />";
}
include("shop_form_shipinfo.inc");
exit();
}
/* Process data when all fields are correct */
$cxn = mysqli_connect($host,$user,$passwd,$dbname);
foreach($_POST as $field => $value)
{
if($field != "Summary" )
{
$value = mysqli_real_escape_string($cxn,$value);
$updates[] = "$field = '$value'";
}
}
$update_string = implode($updates,$cxn);
$sql_ship = "UPDATE CustomerOrder SET $update_string
WHERE order_number='{$_SESSION['order_number']}'";
$result = mysqli_query($cxn,$sql_ship)
or die(mysqli_error($cxn));
extract($_POST);
include("shop_page_summary.inc");
}
elseif(isset($_POST['Ship']))
{
include("shop_form_shipinfo.inc");
}
elseif(isset($_POST['Final']))
{
switch ($_POST['Final'])
{
case "Continue Shopping":
header("Location: shop_products.php");
break;
case "Cancel Order":
#include("shop_page_cancel.inc");
unset($_SESSION['order_number']);
session_destroy();
exit();
break;
case "Submit Order":
$cxn =
mysqli_connect($host,$user,$passwd,$dbname);
$sql = "UPDATE CustomerOrder SET submitted='yes'
WHERE order_number='{$_SESSION['order_number']}'";
$result = mysqli_query($cxn,$sql)
or die("Error: ".mysqli_error($cxn));
#processCCInfo();
#sendOrder();
#include("shop_page_accept.inc");
#email();
session_destroy();
break;
}
}
?>
Here is the affected part of the code:
/* Process data when all fields are correct */
$cxn = mysqli_connect($host,$user,$passwd,$dbname);
foreach($_POST as $field => $value)
{
if($field != "Summary" )
{
$value = mysqli_real_escape_string($cxn,$value);
$updates[] = "$field = '$value'";
}
}
$update_string = implode($updates,","); /* This is the affected area this is how it is in the tutorial I was following. */
$sql_ship = "UPDATE CustomerOrder SET $update_string
WHERE order_number='{$_SESSION['order_number']}'";
$result = mysqli_query($cxn,$sql_ship)
or die(mysqli_error($cxn));
extract($_POST);
include("shop_page_summary.inc");
}
I have tried replacing "," with different fields and I still got the error. the place is suppose to show the order summary.
i just started learning how to code so take anything i say with a major grain of salt, but looking up implode on PHP manual it looks like -
var_dump(implode(",", $array));
so maybe your "," and $updates need to swap places? again i just started so i am probably wrong
I am validating a form data using this script below.
When i submit the form if there is any errors the error message is displaying properly but if no errors and validation succeed i try to echo out the variables to test the script but the script is only displaying this : []
Please examine the code and help me solve this.
<?php
//included files
include("./includes/connect.php");
include("./includes/functions.php");
$errors = array();
//checking if user have submitted the form
if(isset($_POST['submitted'])) {
//validating and cleaning submitted form data ...
if (isset($_POST['name']) && !empty($_POST['name'])) {
if(preg_match("/^[a-zA-Z ]{2,20}$/", strip_trim($_POST['name']))) {
$cln_name = clean_data($_POST['name']);
} else {
$_POST['name'] = FALSE;
$errors[] = "The name you entered is not valid";
}
} else {
$errors[] = "You have not enter your name!";
}
if(isset($_POST['email']) && !empty($_POST['email'])) {
$cln_email = filter_var($_POST['email'] , FILTER_SANITIZE_EMAIL);
if(filter_var($cln_email, FILTER_VALIDATE_EMAIL)) {
$cln_email = clean_data($cln_email);
} else {
$_POST['email'] = FALSE;
$errors[] = "The email you entered is not valid";
}
} else {
$errors[] = "You have not provide you email!";
}
if(isset($_POST['plate_num']) && !empty($_POST['plate_num'])) {
if(ctype_alnum($_POST['plate_num']) && strlen($_POST['plate_num']) >= 5) {
$cln_plate_num = clean_data($_POST['plate_num']);
} else {
$_POST['plate_num'] = FALSE;
$errors[] = "The plate number you provided is not a valid plate number";
}
} else {
$errors[]= "You have not provide a plate number";
}
//checking for errors and printing errors..
if (count($errors > 0)) {
$errors_to_json = json_encode($errors);
echo $errors_to_json;
//foreach ($errors as $error) {
//echo $error . "<br />";
//}
} else {
echo $cln_name . "<br />";
echo $cln_email . "<br />";
echo $cln_plate_num;
}
} else {
echo "You did not submit the form!";
}
?>
This script is returning only this :
[]
Any idea please ??
functions.php :
<?php
function clean_data($data) {
if(function_exists('mysql_real_escape_string')) {
global $dbc;
$data = mysql_real_escape_string(trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string(trim($data));
$data = strip_tags($data);
}
return $data;
}
function strip_trim($data) {
$data = stripslashes(trim($data));
return $data;
}
?>
you have problem in your if condition:
//checking for errors and printing errors..
if (count($errors > 0)) {
...
this will always return to TRUE because $error = [] and count([] > 0) results to TRUE
that's why you always end up in:
$errors_to_json = json_encode($errors);
echo $errors_to_json;
// Will indeed display '[]' because json_encode([]) is '[]'
i believe what you mean here is:
if (count($errors) > 0) {
...
This is function is taking up a lot of lines on my Functions page.
I can't figure out on how to take it down unless putting them into an array, then using a foreach loop. But I want it to be specific on what is not allowed to be blank.
if ($EmployeeID === "")
{
echo "EmployeeID Is Blank.";
}
else
{
if ($Firstname === "")
{
echo "Firstname Is Blank.";
}
else
{
if ($Lastname === "")
{
echo "Last Name Is Blank";
}
else
{
if ($PhoneNumber === "")
{
echo "Phone Number Is Blank";
}
else
{
if ($Address === "")
{
echo "Address Is Blank";
}
else
{
if ($City === "")
{
echo "City Is Blank";
}
else
{
if ($State === "")
{
echo "Sate Is Blank";
}
else
{
if ($Zip === "")
{
echo "Zip Is Blank";
}
else
{
if ($Email === "")
{
echo "Email Is Blank";
}
else
{
if ($Password === "")
{
echo "Password Is Blank";
}
else
{
echo "All Success";
}
}
}
}
}
}
}
}
}
}
The Solution I have Found which takes the lines down, but doesn't give me the exact on what field is left empty is:
$Array = array();
$Array[] = $EmpID;
$Array[] = $FirstName;
$Array[] = $Lastname;
$Array[] = $PhoneNumber;
$Array[] = $Address;
$Array[] = $City;
$Array[] = $State;
$Array[] = $Zip;
$Array[] = $Email;
$Array[] = $Password;
foreach ($Array AS $Checking)
{
if (empty($Checking))
{
echo "One Or More Is Left Blank";
exit;
}
}
try{
if(empty($EmployeeID)){
throw new Exception('EmployeeID Is Blank.');
}elseif(empty($Firstname)){
throw new Exception('Firstname Is Blank.');
}elseif(empty($Lastname)){
throw new Exception('Lastname Is Blank.');
}elseif(empty($PhoneNumber)){
throw new Exception('PhoneNumber Is Blank.');
}elseif(empty($Address)){
throw new Exception('Address Is Blank.');
}elseif(empty($City)){
throw new Exception('City Is Blank.');
}elseif(empty($State)){
throw new Exception('State Is Blank.');
}elseif(empty($Zip)){
throw new Exception('Zip Is Blank.');
}elseif(empty($Email)){
throw new Exception('Email Is Blank.');
}elseif(empty($Password)){
throw new Exception('Password Is Blank.');
}
echo 'All Success';
}catch(Exception $e){
echo $e->getMessage();
}
Maybe you can reorganize it like this:
$messages = array();
if (empty($EmployeeID)){
$messages[] = "EmployeeID Is Blank.";
}
if (empty($Firstname)){
$messages[] = "Firstname Is Blank.";
}
// and so on for the rest.
At the end you can check if $messages is empty to validate:
if (empty($messages)){
echo "All Success";
}else {
echo "Errors:";
foreach($messages as $message){
echo "$message <br>";
}
}
Why are you using al these else statements? I would present all errors all at once to avoid messing with the user (the user fixes the error and then all of a sudden another pops up...).
An easy example:
echo empty($EmployeeID) ? 'EmployeeID Is Blank.' : '';
echo empty($Firstname) ? 'Firstname Is Blank.' : '';
//etc.
I would probably add all error messages to an array and loop through that / check if it is empty:
$errors = array();
if (empty($EmployeeID))
{
$errors['employeeid'] = 'EmployeeID Is Blank.';
}
if (empty($Firstname))
{
$errors['firstname'] = 'Firstname Is Blank.';
}
// etc.
if (count($errors) > 0)
{
// error handling
}
// and you can use the array keys to display the appropriate messages at the appropriate place if it is set:
if (isset($errors['employeeid']))
{
// display the EmployeeID error message where the field should be filled in
}
You could use an associative array like this:
$formValues = array(
'Employee ID' => $EmployeeID,
'First Name' => $Firstname,
'Last Name'=> $Lastname,
'Phone Number'=> $PhoneNumber,
'Address'=> $Address,
'City'=> $City,
'State'=> $State,
'Zip'=> $Zip,
'Email'=> $Email,
'Password'=> $Password,
);
$error=false;
foreach ($formValues as $key => $value) {
if(empty($value)) {
echo($key.' is blank');
$error=true;
}
}
if(!$error) {
echo("All Success");
}
Wrap it all up in a form validator:
<?php
function is_form_valid() {
if ($Firstname === "") { return false; }
if ($Lastname === "") { return false; }
// ...
return true;
}
?>
Of course, this only highlights the idea and you will need to determine the best method for passing in your form fields. Then use that as a single call in your main processing routine:
<?php
if (is_form_valid()) {
// do stuff
} else {
// report error
}
?>
To make it more useful, you can create a shared class for valid input in name fields, emails, etc and call that from your form validation. Imagining such a class exists, your method would look like:
<?php
function is_form_valid() {
if (! $validator->is_valid_name($Firstname)) { return false; }
if (! $validator->is_valid_name($Lastname)) { return false; }
if (! $validator->is_valid_email($Email)) { return false; }
if (! $validator->is_valid_phone($Phone)) { return false; }
// ...
return true;
}
?>
Just be aware of the many regional differences regarding names, phone numbers, addresses, etc. You can read about common pitfalls here. There are also several questions on this forum about the subject of data validation.
Most of the other answers are better, but you should also learn to use elseif():
if ($EmployeeID === "") {
echo "EmployeeID Is Blank.";
} elseif ($Firstname === "") {
echo "Firstname Is Blank.";
} elseif ($Lastname === "") {
echo "Last Name Is Blank";
} //etc
$errors = "";
if($EmployeeID == "")
{
$errors .= "Employee ID blank<br />";
}
if($Firstname == "")
{
$errors .= "First Name blank<br />";
}
if($errors != "")
{
echo $errors;
}
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.
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.