table just inserts one row. there is an auto increment id - php

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.

Related

My code is showing no errmsg but is not inserting any data into database

So I am trying to make a simple e-commerce site. Once I submit the form (btn-submit), I am not able to insert any data to my database. Only the address and contact number verification works.
Here is my code:
if ( isset($_POST['btn-submit']) ) {
// clean user inputs
$oadd = trim($_POST['oadd']);
$oadd = strip_tags($oadd);
$oadd = htmlspecialchars($oadd);
$contact = trim($_POST['contact']);
$contact = strip_tags($contact);
$contact = htmlspecialchars($contact);
// address validation
if (empty($oadd)) {
$error = true;
$oaddError = "Please enter a valid address.";
} else if (strlen($oadd) < 5) {
$error = true;
$oaddError = "Please enter a valid address.";
}
// contact number validation
if (empty($contact)) {
$error = true;
$contactError = "Please enter your contact number.";
} else if (strlen($contact) < 7) {
$error = true;
$contactError = "Contact number must have atleast 7 digits.";
} else if (!preg_match("/^[0-9 ]+$/",$lname)) {
$error = true;
$lnameError = "Please enter a valid contact number.";
}
// if there's no error, continue to place order
if( !$error ) {
$query = 'INSERT INTO cust_order(Order_Date, Order_Status, Order_Total , Address, Contact_No) VALUES (CURDATE(), "in process" , (SELECT SUM(p.Product_Price) FROM cart c, product p WHERE c.Prod_ID = p.Product_ID and c. User_ID = "'.$userRow['User_ID'].'"),"'.$oadd.'","'. $contact.'")';
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Your order has been placed. To view the details, go to your order history";
unset($oadd);
unset($contact);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong. Please try again later.";
}
}
}
What could possibly be wrong with my code? I did similar queries in the other pages but this is the only one not working. Any help would be greatly appreciated! Thanks in advance!
Try to understand the code flow:
if( !$error ) {
// This will only works when **$error is false and the not of false is true**, otherwise this block does not execute
}
So this code works only when there is no validation error occurs in your code and $error contains false
//$userRow is not define any where...
//to check error occur or not :
echo $error;
if(!$error)
{
echo "IN IF";
//also go with die..
$res = mysql_query($query) or die();
}
else
{
echo "IN ELSE";
}

Creating a registration page in PHP

Hi guys so im creating this registration page for my website in php..This is the PHP script
# Script 9.5 - register.php #2
// This script performs an INSERT query to add a record to the users table.
$page_title = 'Register';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Initialize an error array.
// Check for a name:
if (empty($_POST['name'])) {
$errors[] = 'You forgot to enter your name.';
} else {
$n = mysqli_real_escape_string($dbh, trim($_POST['name']));
}
// Check for an email:
if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email.';
} else {
$e = mysqli_real_escape_string($dbh, trim($_POST['email']));
}
// Check for a password and match against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your password did not match the confirmed password.';
} else {
$p = mysqli_real_escape_string($dbh, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your password.';
}
// Check for contact number:
if (empty($_POST['contact_no'])) {
$errors[] = 'You forgot to enter your contact no.';
} else {
$cn = mysqli_real_escape_string($dbh, trim($_POST['contact_no']));
}
if (empty($errors)) { // If everything's OK.
require 'connect_db.php';
$conn= mysqli_connect('*****' , '*****', '*****' , '*****' ,****);
// Make the query:
$q = ("INSERT INTO register_user(name, email, pass, contact_no) VALUES ('$n', '$e','$p','$cn')");
$r = #mysqli_query ($dbh, $q);// Run the query.
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>You are now registered. </p>
<p>Login </p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbh) . '<br/><br/> Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbh); // Close the database connection.
// Include the footer and quit the script:
include ('includes/footer.html');
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br>";
}
echo 'Please try again.</p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbh); // Close the database connection.
But the thing is once i register this is the output:
System Error
You could not be registered due to a system error. We apologize for any inconvenience.
Query: INSERT INTO register_user(name, email, pass, contact_no) VALUES ('', '','','')
so im kindly would glad for any assistance
You're calling mysqli_real_escape_string() BEFORE you establish your DB connection. This is not permitted. You MUST have a connection before doing the escape operations.
That means every single one of your form fields is going to be a boolean FALSE value, which signifies failure.
Your code should be structured
1. connect to db
2. process form inputs
3. if form inputs ok, insert into db
You've got #1 and #2 reversed.

Unable to insert data into mysqli database

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; ?>

Validate Mobile number in php form

I want to validate mobile number of 10 digits and also add a prefix of 0 when I enter into the database.
<?php
include ('database_connection.php');
$citystate = $_POST['citystate'];
$serviceprovider = $_POST['serviceprovider'];
$accept = $_POST['accept'];
if (isset($_POST['formsubmitted'])) {
$error = array(); //Declare An Array to store any error message
if (isset($_POST['checkbox'])) {
$mumbai = (in_array("mumbai", $_POST['checkbox']) ? 1 : 0);
$pune = (in_array("pune", $_POST['checkbox']) ? 1 : 0);
$banglore = (in_array("banglore", $_POST['checkbox']) ? 1 : 0);
$mysore = (in_array("mysore", $_POST['checkbox']) ? 1 : 0);
}
if ($mumbai + $pune + $banglore + $mysore == 0) {
$error[] = 'Please check atleast one SMS center';
}
if ($accept != 1) {
$error[] = 'Please check terms ';
}
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number '; //add to array "error"
}
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number '; //add to array "error"
} else {
$mobile = $_POST['mobileno']; //else assign it a variable
/* if( preg_match("^[0-9]{10}", $mobile) ){
}
else {
$error[] = 'Your Mobile No is invalid ';
} */
}
if (empty($_POST['fname'])) {//if no name has been supplied
$error[] = 'Please Enter a First name '; //add to array "error"
} else {
$fname = $_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 {
$lname = $_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 ($_POST["passwd1"] != $_POST["passwd2"]) {
$error[] = 'Password does not match';
}
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 = '$mobile'";
$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, serviceprovider, pass, fname, lname, email, citystate, MUM, PUN, BNG, MYS ) VALUES ( '" . $mobile . "', '" . $serviceprovider . "', '" . $password . "', '" . $fname . "', '" . $lname . "', '" . $email . "', '" . $citystate . "','" . $mumbai . "', '" . $pune . "', '" . $banglore . "', '" . $mysore . "' )";
}
}
}
Now I get stuck in mobile number validation. I tried using regular expressions.
What I want to do is add a 10 digit phone number and make sure it is only digits or else give error and while entering the number to database I want to add a prefix to the mobile number of 0 so it should be like 0and10digitnumber
Try something like this :
$phoneNumber = $_POST['mobileno'];
if(!empty($phoneNumber)) // phone number is not empty
{
if(preg_match('/^\d{10}$/',$phoneNumber)) // phone number is valid
{
$phoneNumber = '0' . $phoneNumber;
// your other code here
}
else // phone number is not valid
{
echo 'Phone number invalid !';
}
}
else // phone number is empty
{
echo 'You must provid a phone number !';
}
Probably the most efficient and well-readable form would be to use the libphonenumber library from Google. PHP fork is available on GitHub. It can help you not only to validate number itself, but you can check country code with it or even know if some number is valid for specific country (this lib knows which number prefixes are valid for many countries). For example: 07700 900064 is valid GB number, but 09700 900064 is not, even if they have same length.
Here's how I would validate mobile phone number in your app:
$phoneNumber = $_POST['mobileno'];
$countryCode="GB";
if (!empty($phoneNumber)) { // phone number is not empty
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$mobileNumberProto = $phoneUtil->parse($phoneNumber, $countryCode);
if ($phoneUtil->isValidNumber($mobileNumberProto)) { // phone number is valid
//here you know that number is valid, let's try to format it without country code but with 0 at the beginning (national number format)
$phoneNumber = $mobileNumberProto->format($mobileNumberProto, PhoneNumberFormat::NATIONAL);
} else {
$error[] = 'Phone number not valid!';
}
} else {
$error[] = 'You must provide a phone number!';
}
$countryCode is two chars ISO 3166-1 code. You can check it for your country on Wikipedia.
For Indian Mobile Numbers it will be easiest
if(is_numeric($num)){
if($num>=1000000000 && $num<=9999999999){
$num="0".$num;
}
else{
echo "Invalid Mobile Number";
}
}
else{
echo "Hey Buddy mobile numbers are always in digits";
}
This idea struck me because of the willingness of finding easy and some short of mind because the number(1000000000 ) is the lowest numerical value(10 digits) and the number (9999999999) is a highest numerical value that can be used as a mobile number in India.
And one more thing code will run faster than other solutions.
Have you tried a regular expression like:
if( !preg_match("/^([0-1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) {
echo 'Please enter a valid phone number';
}
if(!ereg("^[7-9]{1}[0-9]{9}$", $mob)) { return false; }
Improving pravin tripathi's answer:
if(!ereg("^[7-9]{1}[0-9]{9}$", $mob)) { return false; }
since ereg() is deprecated, you could use
preg_match("/^[7-9]{1}[0-9]{9}$/i", $mobile_no)
This will help you validate a mobile number from India, since they are 10 digits and start with 7, 8 or 9 as of today. You could always change the pattern if new digits get introduced.

having the hardest time passing NULL to my database

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.

Categories