PHP function (adding records) not working correct - php

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?

Related

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

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

PHP Server-Side Validation of Related Fields

I have a user table with userid and password. I would like all form submissions to be 'verified' by another user by entering userid and password before submission. I have a code that works to verify the userid, but I would like to also verify the password, but obviously linked to the userid. This is NOT a login form, all it does is verify that a users entered userid and password are correct.
The 'verify' fields in my form are called: userid_ver and password_ver.
Any help is very appreciated! Thank you.
$rs = CustomQuery("select userid from user where userid = '"
. db_addslashes($values["userid_ver"]) . "'");
if (db_fetch_array($rs)==false)
{
$message = "UserID is incorrect. Please try again.";
return false;
}
$message="";
return true;
I think you made a mistake should be userid_ver = '...
Anyway if you are asking just to add a checking in your query, then add this at the end of your sql statement, just be sure that the $values["password_ver"] is set:
." AND password_ver = '". db_addslashes($values["password_ver"]) . "'"
Complete:
$rs = CustomQuery("select userid from user where userid = '"
. db_addslashes($values["userid_ver"]) . "' AND password_ver = '". db_addslashes($values["password_ver"]) . "'");
if (db_fetch_array($rs)==false)
{
$message = "UserID is incorrect. Please try again.";
return false;
}
$message="";
return true;

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.

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.)

Check record exists db - error show

How do I check if username or email exists and then put a error message in my error array. Right now i have:
$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0)
{
echo "That username or email already exists";
}
But I want to check if it is the username OR the email that is existing and then put:
error[] = "username is existing"; //if the username is existing
error[] = "email is existing"; //if the email is existing
How to do?
It would be easier if you just did a quick true/false check in the SQL and checked the flag that came back.
$sql = "SELECT "
. "(SELECT 1 FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "'), "
. "(SELECT 1 FROM `users` WHERE `email` = '" . mysql_real_escape_string($email) . "')";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
if ($foundFlags['username']) {
$error[] = "username is existing";
}
if ($foundFlags['email']) {
$error[] = "email is existing";
}
} else {
// General error as the query should always return
}
When it does not find an entry, it will return NULL in the flag, which evaluates to false, so the if condition is fine.
Note that you could generalise it for a field list like this:
$fieldMatch = array('username' => $username, 'email' => $email);
$sqlParts = array();
foreach ($fieldMatch as $cFieldName => $cFieldValue) {
$sqlParts[] = "(SELECT 1 FROM `users` WHERE `" . $cFieldName . "` = '" . mysql_real_escape_string($cFieldValue) . "')";
}
$sql = "SELECT " . implode(", ", $sqlParts);
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
foreach ($foundFlags as $cFieldName => $cFlag) {
if ($foundFlags[$cFieldName]) {
$error[] = $cFieldName . " is existing";
}
}
} else {
// General error as the query should always return
}
NB. Note that assumes all fields are strings, or other string-escaped types (eg. date/time).
Sounds like you're trying to let users know whether a username or email already exists at registration time. Here's what you can do:
<?php
//----------------------------------------
// Create first query
$usernameQuery = 'SELECT username FROM users WHERE username="'.mysql_real_escape_string($username).'"';
//----------------------------------------
// Query db
$usernameResult = mysql_query($userNameQuery);
//----------------------------------------
// Check if result is empty
if(mysql_num_rows($usernameResult) > 0){
//----------------------------------------
// Username already exists
$error[] = 'Username already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Check if email exists
//----------------------------------------
// Create query
$emailQuery = 'SELECT email FROM users WHERE email="'.mysql_real_escape_string($email).'"';
//----------------------------------------
// Query the db
$emailResult = mysql_query($emailQuery);
//----------------------------------------
// Check if the result is empty
if(mysql_num_rows($emailResult) > 0){
//----------------------------------------
// Email already exists
$error[] = 'Email already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Continue with registration...
}
}
?>
Please note that you should always escape your values before executing the actual query.
Additional Resources:
http://us.php.net/manual/en/function.mysql-real-escape-string.php
http://us.php.net/manual/en/function.mysql-escape-string.php
You can fetch one row and see if you got same email that you search or same username or both. You can do LIMIT 0,1 if you can stop after finding first row matching either this or that.

Categories