how do i validate if my email is already exist? [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
if(count($_POST)>0) { /* Form Required Field Validation / foreach($_POST as $key=>$value) {
if(empty($_POST[$key])) {
$message = ucwords($key) . " field is required"; break; } } / Password Matching Validation */
if($_POST['password'] != $_POST['confirm_password']){ $message = 'Passwords should be same '; }
/* Email Validation */ if(!isset($message)) { if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) { $message = "Invalid UserEmail"; }
}
/* Validation to check if gender is selected */ if(!isset($message)) { if(!isset($_POST["gender"])) { $message = " Gender field is required"; } }
if(!isset($message)) { require_once("dbcontroller.php"); $db_handle = new DBController();
$query = "INSERT INTO users (username, name, last_name, gender, BirthMonth, BirthDay, BirthYear, Country, email, password, phone) VALUES ('" . $_POST["userName"] . "', '" . $_POST["name"] . "', '" . $_POST["lastName"] . "', '" .$_POST["gender"] . "', '" . $_POST["BirthMonth"] . "', '" . $_POST["BirthDay"] . "' , '" . $_POST["BirthYear"] ."','". $_POST["Country"] ."', '" . $_POST["userEmail"]. "','" . $_POST["password"]. "','".$_POST["Phone"]. "')"; $result = $db_handle->insertQuery($query);
Edit: Format the code to visib;e errors better. Thanks in advance to anyone who answers.

you want to check that your email is exit in database then use this code. add this code after this line .
/* Email Validation */ if(!isset($message)) { if(!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL))
{ $message = "Invalid UserEmail"; }
}
your db connection need to connect for this so first connect this
require_once("dbcontroller.php"); $db_handle = new DBController();
hope your connection is ok so this code will check
<?php
$sql = "SELECT anyfiled FROM yourtable WHERE email = " .$_POST['userEmail'];
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
$message = "exist";
}
?>

Email Validation:
Apart from checking for common symbols like '#' and alpha-numeric, you must also check for white spaces/tabs in start and most importantly convert the incoming input using htmlspecialchars() as:
function reduceInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Call the reduceInput() function on $_POST['userEmail'] and then use your filter_var() funciton to validate it.

I understand you mean not to pass exploiting strings to database? You don't have to validate these values for that. There is a php function which will pass the strings safely to your database. That's it:
mysqli_real_escape_string($mysqli_object, $_POST['userName']);
But if you'd like to validate your email and username, do this:
if (ctype_alnum($nick)==false) exit(0);// this makes your nick can only contain letters and numbers
$emailB = filter_var($email, FILTER_SANITIZE_EMAIL);//this sanitizes your email
if ((filter_var($emailB, FILTER_VALIDATE_EMAIL)==false) || ($emailB!=$email)) exit(0);//this validates your email

Related

PHP function (adding records) not working correct

I am working on a website which will have a user adding form. The following function is addrecord(). When the admin user is creating a new user, this function adds the rows in the SQL table. But, every time I add a new users, I stucked at the error message "User name/password not added to contact", at the first else statement. When I check the table, the access level and password fields are having the data, but I cannot log in with the hashed password. Anybody could help, what's wrong with this code?
Thanks,
Sixxdog
public function addRecord() {
// Verify the fields
if ($this->_verifyInput()) {
// prepare for the encrypted password
$password = trim($_POST['password1']);
// Get the Database connection
$connection = Database::getConnection();
// Prepare the data
$query = "INSERT INTO contacts(first_name, last_name, position, email, phone)
VALUES ('" . Database::prep($this->first_name) . "',
'" . Database::prep($this->last_name) . "',
'" . Database::prep($this->position) . "',
'" . Database::prep($this->email) . "',
'" . Database::prep($this->phone) . "')";
// Run the MySQL statement
if ($connection->query($query)) { // this inserts the row
// update with the user name and password now that you know the id
$query = "UPDATE contacts
SET user_name = '" . Database::prep($this->user_name) . "',
password = '" . hash_hmac('sha512',
$password . '!hi#HUde9' . mysql_insert_id(),
SITE_KEY) ."',
access = '" . Database::prep($this->access) . "'";
if ($connection->query($query)) { // this updates the row
$return = array('', 'Contact Record successfully added.', '');
// add success message
return $return;
} else {
// send fail message
$return = array('', 'User name/password not added to contact.', '');
return $return;
}
} else {
// send fail message and return to contactmaint
$return = array('contactmaint', 'No Contact Record Added. Unable to create record.', '0');
return $return;
}
} else {
// send fail message and return to contactmaint
$return = array('contactmaint', 'No Contact Record Added. Missing required information
or problem with user name or password.', '0');
return $return;
}
}
There's no WHERE clause in your update statement. Perhaps the user_name column has a unique index on it?

Why my mysql transaction is not working properly?

I've been reading and gathering information for 2 days already and I give up. I have no clue why my piece of simple code is not succeeding.
I want to insert data from one form into two tables and YES I know there are exactly same problems described here and there, but as I said I'm familiar with them and also need to ask more questions.
The problem is in my query somewhere, at least this is what I believe it is.
Here it goes:
unset($err);
//Variables
$host = 'my.server.com';
$user = '123';
$pass = 'password';
$dbname = '123';
$err = array();
$error_form = false;
$img = "sth/sth.jpg";
//Connecting to the database using mysqli application programming interface
$con = mysqli_connect($host, $user, $pass, $dbname);
if (!validate()) {
if (!$con) {
echo "Connection failed : <br />" . $new_con->connect_errno . "<br />" . $new_con->connect_error;
exit;
} else {
echo "Connected! <br />";
}
var_dump($name);
echo "<br />";
var_dump($email);
echo "<br />";
var_dump($img);
echo "<br />";
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
echo "<br />";
$_POST["name"] = "";
$_POST["email"] = "";
$_POST["story"] = "";
}
//Form validation
function validate() {
global $name, $email, $story, $err, $error_form;
if($_SERVER['REQUEST_METHOD']=="POST") {
if(isset($_POST["name"]) && !empty($_POST["name"])) {
$name = htmlspecialchars($_POST["name"]);
} else {
$err[0] = "Name is missing.";
$error_form = true;
}
if(isset($_POST["email"]) && !empty($_POST["email"])) {
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$email = htmlspecialchars($_POST["email"]);
} else {
$err[1] = "Email was verified as incorrect.";
$error_form = true;
}
} else {
$err[1] = "Email is missing.";
$error_form = true;
}
if(isset($_POST["story"]) && !empty($_POST["story"])) {
$story = htmlspecialchars($_POST["story"]);
} else {
$err[2] = "Your story does not contain any characters, it can't be submited.";
$error_form = true;
}
}
return $error_form;
}
Everything what confuses me happens here:
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
I've tried to SELECT the id FROM the table1 table and SET it as a #value instead of LAST_INSERT_ID(). I've tried to run two queries...many different solutions.
I found out when I dump mysqli_query($con,$query) it gives false every time unless I don't use transaction, so just simple queries, but I need them.
Last thing is should I use PDO instead of mysqli? Why?
and
Why to use mysqli object oriented style instead of procedural one?
Every help is appreciated. I would like more to understand than just to achieve the effect here.
Be aware this is my first post here, but not the first visit.
You can only do one query at a time with mysqli_query Look at mysqli_multi_query()
http://www.w3schools.com/php/func_mysqli_multi_query.asp
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_multi_query($con,$query));

Submit form with javascript/jquery after php validation

Could someone help me with this problem.
I have to submit a form after I checked if the database doesn't contain the inserted email.
PHP code for email control
$email = $_POST['email'];
$sql = "SELECT * FROM sc_user WHERE email='" . $email . "'";
$select = mysql_query($sql);
$row = mysql_num_rows($select);
$conn_object->connection_signout();
if($row > 0)
echo "exist";
else
echo "notexist";
PHP code for inserting new user in database
if (isset($_POST['submit_registration']))
{
$sql = "INSERT INTO sc_user (name, surname, email, password) VALUES ('" . $_POST['user_name'] . "',
'" . $_POST['user_surname'] . "', '" . $_POST['email'] . "', '" . md5($_POST['password']) . "')";
if (mysql_query($sql))
{
$conn_object->connection_signout();
}
header("Location: index.php");
}
Part of the javascript code I have is this.
$(document).ready(function(){
$("#register_form").submit(function(evReg) {
evReg.preventDefault();
//other code...
$.post('../PHP/checkMail.php', {'email' : email}, function(data) {
if(data == 'exist')
{
$('#email_id').val('');
$('#email_id').attr('placeholder', 'User already registered with this email');
$('#email_id').addClass('placeholder_red');
$('#email_id').focus();
}
else
{
$(this).submit();
}
});
//this.submit();
//other code
If I put "this.submit();" outside "$.Post(...);" block the form will submit corectly, but if is inside it's like it doesn't find the form, I think.
Sorry for the english, I hope you will understand my problem.
I've tried using this
document.getElementById("register_form").submit();
but it doesn't work. I hope I give you all the information you ned.
It doesn't work because you are inside the scope of the callback function of $.post() so $(this) doesn't reference properly to your form, you can try changing your code like this:
$("#register_form").submit(function(evReg) {
evReg.preventDefault();
var $this = $(this);
//other code
and then in your callback function submitting the form using the $this variable
if(data == 'exist')
{
$('#email_id').val('');
$('#email_id').attr('placeholder', 'User already registered with this email');
$('#email_id').addClass('placeholder_red');
$('#email_id').focus();
}
else
{
$this.submit();
}
I haven't tested your code, so i cannot be sure it works but different times this worked for me.

PHP/MySQL log in system -

I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.

Update query not working properly

Ok...I'm using a mySQL DB and this code snippet is part of a login process that is called from a flex coded swf
The code essentially does two things:
1) Checks for existance of a record and then checks period difference if that record exists
If the record exists and is older than six months it will do an update query
2) If no record exists it will use an insert
WHAT"S HAPPENNING...the insert works great...and the update query works except the values for Company and LastName are removed and no value is stored in the database
Why? That is the ten million dollar question...why is the update portion of this code not updating the Company and LastName fields?
Code Below
//This function handles the request from the Update Contact Information popup window in flex to update the records in the database
function updateContactInformation() {
//Initialize variable for result
$Result = false;
//ESTABLISH A CONNECTION WITH THE DATABASE
global $Return;
global $mysql;
global $username;
//ACQUIRE VALUES FROM THE HTTPS REQUEST(FLEX)
//mysql_real_escape_string is used to ensure no code is injected into the input fields
$uUCI_MSUN = mysql_real_escape_string($username); //value used in DB to associate login username with the users formal name
$uUCI_firstname = mysql_real_escape_string($_POST['firstname']);//first name of user
$uUCI_lastname = mysql_real_escape_string($_POST ["lastname"]);//last name of user
$uUCI_company = mysql_real_escape_string($_POST ["company"]);//Name of users company
$uUCI_email = mysql_real_escape_string($_POST["email"]); //email of the user
$uUCI_phone = mysql_real_escape_string($_POST["phone"]); //phone # of the user
//** Note: we do not collect time as the database will automatically update the Last_Updated_Date field with a new timestamp when the record is added or modified
//CHECK TO SEE IF A RECORD EXISTS FOR THE USER ***by checking number of rows returned in a query for login username
if(mysql_num_rows(mysql_query("SELECT MS_UserName FROM usercontactinformation WHERE MS_UserName = '" . $uUCI_MSUN . "'"))){
// UPDATE RECORD IN DATABASE
$query2 = "UPDATE usercontactinformation SET FirstName = '" . $uUCI_firstname . "', LastName = '" . $uUCI_lastname . "', Company = '" . $uUCI_company . "', Email = '" . $uUCI_email . "', Phone = '" . $uUCI_phone ."' WHERE idUserContactInformation = " . getUID($username) . " ;";
//send Request to mySQL
$Result = mysql_query($query2, $mysql);
} else {
//INSERT NEW RECORD INTO DATABASE
$query ="INSERT INTO usercontactinformation (MS_UserName,FirstName,LastName,Company,Email,Phone) VALUES('" . $uUCI_MSUN . "','" . $uUCI_firstname . "','" . $uUCI_lastname . "','" . $uUCI_company . "','" . $uUCI_email . "','" . $uUCI_phone . "');";
//send Request to mySQL
$Result = mysql_query($query, $mysql);
}
//RETURN A RESULT TO FLEX
if ($Result) {
$Return .= "<SuccessCode>1</SuccessCode>";
} else {
$Return .= "<SuccessCode>0</SuccessCode>";
}
}
function getUID($username) {
global $mysql; //access Global mysql connection
//Create Query to verify user exists and check difference between current date and Date Last Modified for the Users Contact Information
$query = "Select idUserContactInformation from mydatabasename.UserContactInformation where MS_username = '" . $username . "'";
//Send The Query To the SQL server
$result = mysql_query($query, $mysql);
//parse results and return access level to calling function
while ( $User = mysql_fetch_object( $result ) ) {
return $User->idUserContactInformation;
}
}
$Return .= "</Result>";
print ($Return)
Somone asked for the form values...the below code is a snippet from flex that passes the form value to the PHP file
public function useHttpService():void {
//Alert.show("Use HTTPS");
service = new HTTPService();
service.method = "POST";
service.useProxy = false;
service.url = parentApplication.relativeDir + "/somepath/phpfileprocessinginformation.php";
service.request.req = "updateContactInformation";
service.request.username = parentApplication.User.username;
service.request.password = parentApplication.User.password;
//pass user supplied new information to query
service.request.firstname = firstname.text;
service.request.lastname = lastname.text;
service.request.company = company.text;
service.request.email = email.text;
service.request.phone = phone.text;
service.addEventListener(ResultEvent.RESULT, httpResult);
service.addEventListener(FaultEvent.FAULT, httpFault);
service.send();
}
You have extra spaces in the two lines of code where you should be getting those values:
... $_POST ["lastname"]);//last name of user
... $_POST ["company"]);//Name of users company
That is not the same as:
... $_POST["lastname"]);//last name of user
... $_POST["company"]);//Name of users company
HTH.
Not a big PHP guy -- found this question when looking through the MySQL stuff -- so I'm not sure this is valid at all, but where you're setting the lastname and company variables you have a space between $_POST and the bracket ([), could that be the problem? (The other ones don't have the space.)

Categories