Update query not working properly - php

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

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

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;

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.

Insert php record from mysql table into a different table

I've been searching for a long time for a solution to what I feel is a very simple problem.
I have a dynamically created page with a video that has a unique id. I also have a form that a user can submit content with. I want the id of the video to be included in the submission to tableA.
This code works great only when $id = 1.
$vidq = "SELECT * FROM tutorials";
$vidresult = mysql_query($vidq);
$vidrow = mysql_fetch_array($vidresult);
//form submission
if($_POST['formname'] == "submit") {
$name = $_POST['name'];
$id = $vidrow['id'];
$errorMessage = "";
if(empty($name)) {
$errorMessage .= "<li>Please enter a valid name</li>";
}
if(empty($errorMessage)) {
$insert = "INSERT INTO tableA (videoid, name) VALUES (".$id.", ".$name.")";
mysql_query($insert);
exit();
}
}
When I change $id to = 1, it posts, but when $id to = $vidrow['id'] it doesn't post.
What am I doing wrong?
Try displaying the mysql error message by using mysql_errno/mysql_error. Eg...
if (!mysql_query($insert))
{
die('MySQL Fail (' . mysql_errno() . ') - ' . mysql_error());
}
mysql_errno() documentation - http://php.net/manual/en/function.mysql-errno.php
Have you tried to print out the contents of $id after $id = $vidrow['id'];? It might reveal why it doesn't work the way you want...
Have you thought about what might happen if a malicious (or just curious) user calls your script with ?name=%27%27%29%3b%20DROP%20TABLE%20tableA%3B?

Categories