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.
Related
I have script that make comparison between value from page php and data store in txt file, and then it will do some special code.
Content of txt file (account.txt)
F: user pass { expire=date; afexpire=date; email=email#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
F: mike fghg58g { expire=2016-05-24; afexpire=2015-5-24 17; email=mike#gmail.com; Country=uk; visit_from=none; ip=none; hosted=none }
F: adresson f5849dh9d { expire=2016-11-01; afexpire=2015-11-01 17; email=mike#gmail.com; Country=Germani; visit_from=none; ip=none; hosted=none }
my script
<?php
$user = "Mike"; // user that is inserted in page form
$email = "mike#gmail.com"; // email that is inserted in page form
$userFile = "Mike"; // user in txt file
$emailFile = "mike#gmail.com"; // email in txt file
if( $user == $userFile && $email == $emailFile ) {
echo "The user and email is used";
} elseif( $user == $userFile && $email != $emailFile ) {
echo "The user is used";
} else{
// do special code
}
I don't know how to read file txt from path and change user and email in file to value to make comprison
$userFile = "Mike"; // user in txt file (account.txt)
$emailFile = "mike#gmail.com"; // email in txt file (account.txt)
This is my spcial script that make output in (account.txt)
<?php
if (isset($_POST["g-recaptcha-response"])) {
$name = $_POST['name'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$country = $_POST['country'];
$plan = $_POST['plan'];
$quantity = $_POST['quantity'];
$payment = $_POST['payment'];
$reciever = $_POST['reciever'];
$captcha = $_POST['g-recaptcha-response'];
$message_user = $_POST['message'];
$serverip = $_POST['REMOTE_ADDR'];
$to = 'sup.alphas#gmail.com';
$parts = explode("#", $email);
$sufemail = $parts[0];
// $sufemail = substr(strstr($email, '#'), 1); for domain//
$subject_form = 'Request new account by '.$sufemail.'';
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if name has been entered
if (!$_POST['user']) {
$errUser = 'Please enter your username';
}
// Check if name has been entered
if (!$_POST['pass']) {
$errPass = 'Please enter your password';
}
// Check if email has been entered and is valid
if (!$_POST['email']) {
$errEmail = 'Please enter a valid email address';
}
if (!$_POST['country']) {
$errCountry = 'Please enter your country';
}
if (!$_POST['plan']) {
$errPlan = 'Please enter your plan';
}
if (!$_POST['quantity']) {
$errQuantity = 'Please enter your quantity';
}
if (!$_POST['payment']) {
$errPayment = 'Please enter your method of payment';
}
if (!$_POST['g-recaptcha-response']) {
$errCaptcha = 'Please enter captcha';
}
// If there are no errors, send the email
if (!$errName && !$errUser && !$errPass && !$errEmail && !$errCountry && !$errPlan && !$errQuantity && !$errPayment && !$errCaptcha) {
// Start Create new account //
$dateadd = date('Y-m-d', strtotime("$plan"));
$datetry = date('Y-m-d H', strtotime("+1 day"));
$handle = fopen('/usr/www/users/alphacz/alpha/phpm/account.cfg', 'a');
fwrite($handle, 'F: ' . $_POST["user"] . ' ' . $_POST["pass"] . ' { expire=' . $datetry . '; afexpire=' . $dateadd . '; email=' . $email . '; Country=' . $country . '; visit_from=none; ip=none; hosted=' . $_POST['REMOTE_ADDR'] . " }\r\n");
fclose($handle);
Help me, please
Thank you
You can check a needle in a haystack which is your account file here.
username pattern is "F: {user} pass {..."
email pattern is "; email={email}; Country="
Note: You must also think that this excample check keywords incasesensitive, so
when searching and inserting, you should convert keywords to lowercase
$user_used = userExists('Mike');
$email_used = emailExists('mike#gmail.com');
if ($user_used && $email_used)
{
echo 'The user and email is used';
}
elseif ($user_used) {
echo 'The user is used';
}
else
{
//do special code
}
function userExists($user)
{
return (exec('grep ' . escapeshellarg('F: ' . $user . ' ') . ' {file-path}'));
}
function emailExists($email)
{
return (exec('grep ' . escapeshellarg('; email=' . $email . ';') . ' {file-path}'));
}
We could fix your current code to read from the file, but instead we first rewrite your code which writes to the file, so it will be way easier to read from the file afterwards.
(Since you only show part of the script which writes to the file I can only rewrite that part.)
Changes
JSON format for the file
Instead of writing your data into the file in a custom format we will save the data in JSON format. You can easily work with JSON in PHP since it has built-in functions to work with it.
$_POST ↔ $_SERVER ?
At some point you use $_POST['REMOTE_ADDR'], but I assume that you wanted to use $_SERVER["REMOTE_ADDR"]. See: http://php.net/manual/en/reserved.variables.server.php.
!$XY
While using !$XY as condition may work sometimes it isn't very practical. Since it simply negates the value and then checks if it is a truthy or falsey value and should enter the if statement or not. So I would recommend you to use !empty() to check if your input is set and is not empty.
Code
<?php
if (isset($_POST["g-recaptcha-response"])){
$checkPostIndices = ["name", "user", "pass", "email", "phone", "country", "plan", "quantity", "payment", "reciever", "g-recaptcha-response", "message"];
$data = [];
$errors = [];
$errorMessages = [
"name" => "Please enter your name",
"user" => "Please enter your username",
"pass" => "Please enter your password",
"email" => "Please enter a valid email address",
"phone" => "Please enter your phone number",
"country" => "Please enter your country",
"plan" => "Please enter your plan",
"quantity" => "Please enter your quantity",
"payment" => "Please enter your method of payment",
"reciever" => "Please eneter a reciever",
"g-recaptcha-response" => "Please enter captcha",
"message" => "Please enter a message",
];
foreach($checkPostIndices as $index){
if(!empty($_POST[$index])){
$data[$index] = $_POST[$index];
} else {
$errors[] = $errorMessages[$index];
}
}
$data["serverip"] = $_SERVER["REMOTE_ADDR"];
$to = "sup.alphas#gmail.com";
$sufemail = explode("#", $data["email"])[0];
$subject_form = "Request new account by " . $sufemail;
if(!empty($errors)){
$fileData = array_intersect_key($data, ["user", "pass", "email", "country", "serverip"]);
$fileData["dateadd"] = date("Y-m-d", strtotime($data["plan"]));
$fileData["datetry"] = date("Y-m-d H", strtotime("+1 day"));
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$file = empty($file) ? [] : json_decode($file, TRUE);
$file[] = $fileData;
file_put_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg", json_encode($file));
}
}
?>
So now after that your data should be stored in JSON like this:
[
{"key":"data"}
//...
]
And then you can easily use json_decode() to decode your file into an array, loop through the array and check if the email and user are already used.
Code
<?php
$user = "Mike";
$email = "mike#gmail.com";
$file = file_get_contents("/usr/www/users/alphacz/alpha/phpm/account.cfg");
$data = json_decode($file, TRUE);
foreach($data as $v){
if($v["user"] == $user && $v["email"] == $email){
echo "Email and user already used";
}
}
?>
I am trying to make a registration form and doing some checks before running SQL queries, but as i test and try to generate multiple errors, i am getting only the error that comes first, or sometimes no error at all. I am unable to locate where i have made error.
The following is the code in PHP.
//function to filter only phone numbers
function get_phone($number) {
return preg_replace('#[^0-9]#', '', $number);
}
//function to take only alphabets.
function get_alpha($alphabets){
return preg_replace('#[^a-z]#', '', $alphabets);
}
//function to check email.
function isValidEmail($email){
if (strlen ($email) > 50){
$errors[] = 'email address too long, please use a shorter email address..!';
} else {
return (filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
function output_errors($errors){
$output = array();
foreach($errors as $error) {
$output[] = '<li>' . $error . '</li>';
}
return '<ul>' . implode('', $output) . '</ul>';
}
if (empty($_POST) === false) {
//store the text box field names of the form to local variables.
$cust_name = $_POST['name1'];
$cust_email = $_POST['email'];
$cust_phone = $_POST['phone'];
$cust_addr1 = $_POST['addr1'];
$cust_addr2 = $_POST['addr2'];
$cust_city = $_POST['city'];
$cust_state = $_POST['state'];
$cust_country = $_POST['country'];
$username = $_POST['uname'];
$password = $_POST['passwd'];
$cnf_passwd = $_POST['cnf_passwd'];
$sec_que = $_POST['sec_que'];
$sec_ans = $_POST['sec_ans'];
//sanitize the inputs from the users end.
$cust_name = sanitize($username);
$cust_phone = get_phone($cust_phone);
$cust_addr1 = sanitize($cust_addr1);
$cust_addr2 = sanitize($cust_addr2);
$cust_city = get_alpha($cust_city);
$cust_state = get_alpha($cust_state);
$cust_country = get_alpha($cust_country);
$username = sanitize($username);
$password = md5($password);
$cnf_passwd = md5($cnf_passwd);
$sec_que = sanitize($sec_que); //put up dropdown menu
$sec_ans = sanitize($sec_ans);
$cust_email = isValidEmail($cust_email);
//check for error handling in form data
//1. check for empty fields,
if ($cust_name == "" || $cust_phone == "" ||
$cust_addr1 == "" || $username == "" ||
$password == "" || $cnf_passwd == "" ||
$sec_que == "" || $sec_ans == ""
) {
$errors[] = 'No blank fields allowed, please fill out all the required fields..!';
//2.check for field lengths
} else if (strlen($cust_name) < 3 || strlen($cust_name > 20)) {
$errors[] = 'The name length should be between 3 to 20, please check & correct..!';
//3. check for phone number length
} else if (strlen($cust_phone) < 10 || strlen($cust_phone) > 11) {
$errors[] = 'The phone number must be 10 or 11 digits..!';
//4. check for address input lengths.
} else if (strlen($cust_addr1) < 5 || strlen($cust_addr1) > 50) {
$errors[] = 'Please provide a valid address..to serve you better..!';
//5. check if the password fields content match.
//length is not checked because the entered values will be converted to MD5 hash
// of 32 characters.
} else if ($password != $cnf_passwd) {
$errors[] = 'The passwords do not match. Please enter your passwords again..!';
// 6. check for length of the security answers.
} else if (strlen($sec_ans) < 5 || strlen($sec_ans) > 50) {
$errors[] = 'Please enter a proper security answer..!';
} //7. check for valid email address
else if($cust_email == false){
$errors[] = 'The email address you entered is not valid, please check and correct..!';
} else {
execute the SQL queries and enter the values in the database.
echo 'GOOD...TILL NOW..!!!';
}
} else {
$errors [] = 'No data received, Please try again..!!';
}
if(empty($errors) === false) {
?>
<h2>The Following errors were encountered:</h2>
<?php
echo output_errors($errors); //output the errors in an ordered way.
}
?>
When you use this structure:
if () {
} else if () {
} else if () {
}
// etc.
then only one condition can be satisfied. As soon as one of those if conditions is true, the rest of the else if blocks and the final else block are ignored.
If your conditions aren't mutually exclusive, put them in their own separate blocks:
if () {
}
if () {
}
if () {
}
// etc.
This is my register form,after i add validation and my record can't insert into database.But my validation are working.If i exchange the code of validation and mysql,all can insert into database even if got error in my validation.
<?php
$fnameErr=$lnameErr=$passErr=$repassErr=$icErr=$emailErr=$add1Err=$add2Err=$postErr=$mobileErr="";
$fname=$lname=$pass=$repass=$ic=$email=$add1=$add2=$postcode=$mobile="";
if (isset($_POST['submitbtn']))
{
$fname = $_POST['bname'];
$lname = $_POST['lname'];
$pass = $_POST['bpass'];
$repass = $_POST['bconpass'];
$ic = $_POST['bic'];
$email = $_POST['bemail'];
$add1 = $_POST['badd1'];
$add2 = $_POST['badd2'];
$postcode = $_POST['bpostcode'];
$mobile = $_POST['bmobile'];
$country = $_POST['bcountry'];
$state = $_POST['bstate'];
$city = $_POST['bcity'];
$gen = $_POST['bgender'];
if($fname==""||$lname==""||$pass==""||$repass==""||$ic==""||$email==""||$add1==""||$add2==""||$country==""||$state==""||$postcode==""||$mobile==""||$city==""||$gen=="")
{
?>
<script type="text/javascript">
alert("Please fill in all the required informations.");
</script>
<?php
}
if (empty($errors) === true)
{
//bemail
if (filter_var($_POST['bemail'], FILTER_VALIDATE_EMAIL) === false)
{
$emailErr = 'A valid email address is required';
}
else if (email_exists($_POST['bemail']) === true)
{
$emailErr= 'Sorry, the email \'' . $_POST['bemail'] . '\' is already in use';
}
//fname xx
if (!preg_match("/^[A-Z][a-zA-Z -]+$/i",$_POST['bname']))
{
$fnameErr= 'Your first name cannot contain with any symbol and number';
}
//lname xx
if (!preg_match("/^[A-Z][a-zA-Z -]+$/i",$_POST['lname']) )
{
$lnameErr= 'Your last name cannot contain with any symbol and number';
}
//ic xx
if(!preg_match("/^\d{6}-\d{2}-\d{4}$/i", $_POST['bic']))
{
$icErr= 'Your ic cannot contain any character / must insert "-"';
}
//mobile xx
if (!preg_match("/^\d{3}-\d{7}$/i", $_POST['bmobile']))
{
$mobileErr= 'Phone must comply with this mask: 010-1111111 or 0111-1111111';
}
//password
if (strlen($pass) < 6)
{
$passErr = 'Your password must be at least 6 characters';
}
//re-password
if ($_POST['bpass'] !== $_POST['bconpass'])
{
$repassErr= 'Your password do not match';
}
//add1 xx
if (!preg_match("/^[a-zA-Z0-9 _.,:\"\']+$/i", $_POST['badd1']))
{
$add1Err = 'Address 1 must be only letters, numbers or one of the following';
}
//add2 xx
if (!preg_match("/^[a-zA-Z0-9 _.,:\"\']+$/i",$_POST['badd2']))
{
$add2Err= 'Address 2 must be only letters, numbers or one of the following';
}
//postcode xx
if (!preg_match("/^\d{5}$/i", $_POST['bpostcode']))
{
$postErr = 'Postcode must be 5 digits';
}
?>
<script type="text/javascript">
alert("Register have some error,please complete your informations.");
</script>
<?php
}
else
{
$result = mysql_query("select * from member where Member_Email='$email'");
if (mysql_num_rows($result)==0)
{
mysql_query("insert into member(Member_Name,Member_Lname,Member_Pass,Member_IC,Member_Email,Member_Street1,Member_Street2,Member_Country,Member_State,Member_Postcode,Member_HP,Member_City,Member_Gen) VALUES ('$fname','$lname','$pass','$ic','$email','$add1','$add2','$country','$state','$postcode','$mobile','$city','$gen')");
header("Location:all_login.php");
?>
<script type="text/javascript">
alert('Registered successfully!');
</script>
<?php
}
else
{
?>
<script type="text/javascript">
alert("email address already exists!");
</script>
<?php
}
}
}
?>
I'm so sorry with my poor english.
if (empty($errors) === true)
At no point before this in the code you posted do you define $errors. As per the PHP doc on that function, if the variable doesn't exist then empty() will return true. So unless you've left something out, your code will always enter the first part of the if statement and not the second.
I suspect that you want to change that line to if (empty($errors) === false) so that you only enter that part of your code if there is an error.
You should be really carefull for usage of variable like $test should be '.$test.' if string. Also you should use mysqli
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.