SQL insert in php not working - php

Im very new to php and trying to get a register up and working , my code at the minute is only loading the username into the database and nothing else. Although it does enter values into other fields of the database if I hard-code them into sql insert and dont use
$users_Password
etc. btw I know this is terrible code and passwords should be hashed etc but ive literally just tore this code apart because this wont work and will add everything back in after this is sorted out cheers , this is my code
form
<form id = "Register_form" action="Register.php" method="post">
Username: <input type="text" name="Username"><br>
Password: <input type="password" name="Password"><br>
Confirm Password: <input type="password" name="ConfirmPassword"><br>
First Name: <input type="text" name="FirstName"><br>
Surname: <input type="text" name="Surname"><br>
Address Line 1: <input type="text" name="AddressLine1"><br>
Address Line 2: <input type="text" name="AddressLine2"><br>
City: <input type="text" name="City"><br>
Telephone: <input type="text" name="Telephone"><br>
Mobile: <input type="text" name="Mobile"><br></br>
<input type="submit">
then in the Register.php file
<?php
// create connection
$con=mysqli_connect("localhost","root","","book");
// check connection
if(mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$users_Username = $_POST['Username'];
$users_Password = $_POST['Password'];
$users_ConfirmPassword = $_POST['ConfirmPassword'];
$users_FirstName = $_POST['FirstName'];
$users_Surname = $_POST['Surname'];
$users_AddressLine1 = $_POST['AddressLine1'];
$users_AddressLine2 = $_POST['AddressLine2'];
$users_City = $_POST['City'];
$users_Telephone = $_POST['Telephone'];
$users_Mobile = $_POST['Mobile'];
//Multiple Error checkings such as
if ($users_Username == "")
{
echo "Please enter a username";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
else if ($users_Password = "")
{
echo "Please enter a password";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
else if ($users_ConfirmPassword == $users_Password)
{
if (strlen($users_Password)<=6)
{
$sql = "INSERT INTO users VALUES ('$users_Username', '$users_Password', '$users_FirstName', '$users_Surname','$users_AddressLine1','$users_AddressLine2','$users_City','$users_Telephone','$users_Mobile')";
if($con->query($sql) === TRUE)
{
echo "User succesfully registered";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Log_In_Screen.php';\",1500);</script>";
}
else
{
echo "Unable to register user, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
//echo "<pre>\n$sql\n</pre>\n";
mysql_query($sql);
}
else
{
echo "The password you entered is too long, max characters is 6";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
}
else
{
echo "Passwords do not match, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
mysqli_close($con);
?>
It seems like nothing will insert into the database except the username , any one have a way to fix this ?
Cheers

You had stuff all over the place and were mixing mysql and mysqli not to mention you left yourself wide open for SQL injection. Using the script you had I stuck with mysqli used prepared statements and split your validation and persistence up. There are comments that will explain some of this
<?php
$users_Username = $_POST['Username'];
$users_Password = $_POST['Password'];
$users_ConfirmPassword = $_POST['ConfirmPassword'];
$users_FirstName = $_POST['FirstName'];
$users_Surname = $_POST['Surname'];
$users_AddressLine1 = $_POST['AddressLine1'];
$users_AddressLine2 = $_POST['AddressLine2'];
$users_City = $_POST['City'];
$users_Telephone = $_POST['Telephone'];
$users_Mobile = $_POST['Mobile'];
//LETS JUST DO ERROR CHECKING ONLY
$valid = true; //Used to verify that user input is as expected.
//All the validation as before just as ifs and will set the
//$valid flag to false when validation fails.
if ($users_Username == "")
{
$valid = false;
echo "Please enter a username";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if ($users_Password = "")
{
$valid = false;
echo "Please enter a password";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if (strlen($users_Password)>6)
{
$valid = false;
echo "The password you entered is too long, max characters is 6";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if ($users_ConfirmPassword != $users_Password)
{
$valid = false;
echo "Passwords do not match, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
//Separating validation and persistence mean you only
//open a connection and persist when needed.
if($valid)
{
//NOW WE ONLY CONNECT WHEN YOU NEED TO!
$con=mysqli_connect("localhost","root","","book");
// check connection
if(!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//YOU MAY NEED TO SPECIFY THE COLUMNS YOU ENTER
$stmt = mysqli_prepare($con, "INSERT INTO users VALUES (?,?,?,?,?,?,?,?,?)");
//ASSUMING ALL 9 PARAMETERS ARE STRINGS hence the sssssssss
mysqli_stmt_bind_param($stmt, 'sssssssss', $users_Username,$users_Password,$users_FirstName,$users_Surname,$users_AddressLine1,$users_AddressLine2,$users_City,$users_Telephone,$users_Mobile);
if(mysqli_stmt_execute($stmt))
{
echo "User succesfully registered";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Log_In_Screen.php';\",1500);</script>";
}
mysqli_close($con);
}
?>

What content lands in your database?
Try the following in the appropriate line:
"INSERT INTO users VALUES ('".$users_Username."', '".$users_Password."', '".$users_FirstName."', '".$users_Surname."','".$users_AddressLine1."','".$users_AddressLine2."','".$users_City."','".$users_Telephone."','".$users_Mobile."')";
PHP Params cant be evaluated in ' ' so you have to use string concatenation.

Related

php check and validate form input with mysql database [duplicate]

This question already has an answer here:
PHP's white screen of death [duplicate]
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
Basically I have this form that asks for email and password.
What I want to do is to compare and check if the inputs match with the data from my table/database.
This is my registration.php (the form)
<form action="Authentication.php" method="post">
<b>Returning Intern Login</b><br/><br/>
Enter your e-mail address: <input type="text" name="email" /><br/><br/>
Enter your password: <input type="password" name="pw2"/><br/><i>(Passwords are case-sensitive and must be 6 characters long)</i><br/><br/>
<input type="reset" value="Reset Login Form" />
<input type="submit" name="submit2" value="Log In" /><hr/><br/>
</form>
and this is the Authentication.php
session_start();
$link = mysqli_connect('localhost','root','');
$database = mysqli_select_db($link,'internship');
$user = $_POST['email'];
$pass = $_POST['pw2'];
// User is logging in
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
It works with the empty inputs.
But when I gave an email and password exactly same from the database/table,
It displays white blank page..
You need to write the entire code within an if statement to ensure the field is filled in, like so:
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
/* Code */
}
if (empty ($pass)) //if password field is empty echo below statement
{
/* Code */
}
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
else
{
echo "Empty input submit2"; // empty $_POST["submit2"]
}
Hope this helps.
Mysqli takes 4 parameters hostname,username,password, and dbname:
<?php
session_start();
$link = mysqli_connect('localhost','root','','internship');
// User is logging in
if (isset($_POST["submit2"]))
{
$user = $_POST['email'];
$pass = $_POST['pw2'];
if (empty($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
else if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". $user ."' AND password = '".$pass."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
?>

Checking if username exists POSTBACK

I want to check using the POSTBACK method i the user exists in mysql table. I studying mysql and i understand it will be removed soon but I cant change at the moment. I want the alert to pop up next to the username text box if it already exists.At the moment it isnt working. I have a similar code for password and password confirmation but i think this differs since i need a query. This is what i have:
<?php
$passErr = $pass1Err = "";
$passw = $passw1 = "";
$userErr="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["password"])) {
$passErr = "Password is required";
}
if (empty($_POST["passconfirm"])) {
$pass1Err = "Password confirmation is required";
}
if ($_POST['password']!= $_POST['passconfirm'])
{
$passErr = "Passwords must be the same";
$pass1Err = "Passwords must be the same";
}
}
else {
if (isset($_REQUEST["submit"]))
{
if (isset($_POST["submit"]))
{
$firstname = mysql_real_escape_string($_POST["gname"]);
$middlename = mysql_real_escape_string($_POST["mname"]);
$lastname = mysql_real_escape_string($_POST["surname"]);
$user = mysql_real_escape_string($_POST["username"]);
$addy = mysql_real_escape_string($_POST["address"]);
$post = mysql_real_escape_string($_POST["postcode"]);
$sta = mysql_real_escape_string($_POST["state"]);
$telephone = mysql_real_escape_string($_POST["tel"]);
$pass = mysql_real_escape_string($_POST["password"]);
$systemuser= mysql_real_escape_string($_POST["susername"]);
$sql2 = "SELECT username FROM users WHERE username= '$user'";
$rs = mysql_query($sql2, $conn)
or die ('Problem with query' . mysql_error());
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
if($num_rows != 0){
$userErr = "Username already exists";
}
}
}
}
mysql_close($conn);
}
?>
this is what i got in the form:
<label>Chosen Username:</label> <input type="text" name="username" value="<?php
echo $userErr;?>"/><span class="error">* <?php echo $userErr;?></span><br />
<label>Password:</label> <input type="password" name="password" value="<?php
echo $passw;?>"/><span class="error">* <?php echo $passErr;?></span><br />
<br />
<label>Password confirmation:</label> <input type="password" name="passconfirm" value="<?php
echo $passw1;?>"/><span class="error">* <?php echo $pass1Err;?></span><br />
To acheive what your looking for, instead of using
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
if($num_rows != 0){
$userErr = "Username already exists";
}
}
replace it with
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
$userErr = "Username field cannot be empty";
}elseif($num_rows > 0){
$userErr = "Username already exists";
}
That way if the Username field is empty, it will error out. And this will also achieve your goal of checking the database to see if the user exists or not.
You need to know if request with username return something so error messsage else do insert new user,
$sql2 = "SELECT * FROM users WHERE username= '$user'";
$rs = mysql_query($sql2, $conn) or die ('Problem with query' . mysql_error());
if($num_rows=mysql_fetch_array($rs)){
$userErr = "Username already exists";
// ....
} else{
// $SQL = "INSERT INTO users SET ...
}

HTML FORM + PHP: form action to remain on same page as login

at the moment my form links to a new page with all of my php code on it. I would like for all of the code to be executed on the same page as it does in this tutorial: http://www.w3schools.com/php/php_form_url_email.asp
I'm having some difficulty understanding exactly how this tutorial manages it. I was thinking maybe it would be possible to store my add.php code in a function and then call it with form action. Is this possible? If not what would be the best way to go about this?
here is my form code:
<form action="add.php" method="post">
<p>
Username: <input type="text" name="Username"><br>
Email: <input type="text" name="Email"><br>
Password: <input type="password" name="Password"><br>
Confirm Password: <input type="password" name="ConfirmPass">
</p>
<p>
<input type="submit">
</p>
</form>
and here is my add.php page:
<?php
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
$ConfirmPass = $_POST['ConfirmPass'];
$safeUsername = SQLite3::escapeString($Username);
$safePassword = SQLite3::escapeString($Password);
$safeEmail = SQLite3::escapeString($Email);
$safeConfirmPass = SQLite3::escapeString($ConfirmPass);
$hostName = explode('#', $Email);
$database = new PDO('sqlite:maindb.db');
$sql = "SELECT * FROM users WHERE Username = ?";
$result = $database->prepare($sql);
$result->bindParam(1, $safeUsername);
$result->execute();
if($result->fetch()) {
echo "Username " . $safeUsername . " already exists";
}
else {
if (filter_var($safeEmail, FILTER_VALIDATE_EMAIL) && checkdnsrr($hostName[1]) && !empty($safeEmail)) {
if (preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$safeEmail)) {
if (!empty($safeUsername) && (preg_match("/^[a-zA-Z ]*$/",$safeUsername)) && !empty($safeUsername)) {
if ($safePassword == $safeConfirmPass && !empty($safePassword)) {
echo $Username . " was successfully added to the database.";
$stm = "INSERT INTO users(Username, Password, Email) VALUES(?,?,?)";
$stmt = $database->prepare($stm);
$stmt->bindParam(1, $safeUsername);
$stmt->bindParam(2, $safePassword);
$stmt->bindParam(3, $safeEmail);
$stmt->execute();
$database = null;
}
else {echo "Passwords do not match"; }
}
else {echo "Invalid Username.";}
}
else {echo "Invalid e-mail address.";}
}
else {echo "Invalid e-mail address.";}
}
?>
Thanks for the help! I appreciate it.
In the tutorial you linked they use
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//your stuff here
//save your form values etc.
}
to check if there has been a post to your page (this can be any page so also the same page). Basically this will check if a POST request has been send to this page. Which will if you use a from with a post method.
As an extra test they also put stuff like
if (empty($_POST["name"])) {
//name is empty print error!
}
in it to check if a field is empty or not.
all you gotta do now is change your action to the same page.

Stop empty values from input boxes from being inserted into my database? PHP

This is the html form (register.php):
<html>
<body>
<form action="handle_registration.php" method="post">
<fieldset><legend>Enter your
information in the form below:</legend>
First Name: <input type="text" name="fname" size="20" maxlength="40"><br>
Last Name: <input type="text" name="lname" size="20" maxlength="40"><br>
Username: <input type="text" name="uname" size="20" maxlength="40"><br>
Password: <input type="text" name="pword" size="20" maxlength="40"><br>
<input type="submit" name="submit" value="submit my info">
</form>
</body>
</html>
This is the php script that handles the registration (handle_registration.php):
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "registration_info";
$con = mysqli_connect("$db_host", "$db_user", "$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Make sure all of the input boxes have a value:
if (empty($fname)) {
die('You forgot to enter your first name!');
}
if (empty($lname)) {
die('You forgot to enter your last name!');
}
if (empty($uname)) {
die('You forgot to choose a username!');
}
if (empty($pword)) {
die('You forgot to choose a password!');
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);
?>
Here's the problem:
I want to submit the entered values into my database if all of the input fields have a value, but when I use the die function after checking to see if they're empty, then it kills the script. I just want to kill the part were it inserts it into my database if one or more of the fields are empty & display an error message that tells which field was empty. I'm not sure how to get around this and any help will be greatly appreciated.
The solution is rather simple. Just store the error message in a variable and before inserting rows into the DB - check weather the error is set or if it's empty. If it's empty - we can insert the row. Otherwise - let's show the error message.
// Currently we do not have an error
$error = NULL;
// Validate
if (empty($pword)) {
$error = 'You forgot to choose a password!';
}
// If there are no errors - lets insert
if (!$error) {
$sql = 'INSERT INTO ...';
}
DOn't use die ,use some variable to store errors and print them later
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname']; $lname = $_POST['lname']; $uname =
$_POST['uname']; $pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name =
"registration_info"; $con = mysqli_connect("$db_host", "$db_user",
"$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ()) { echo "Failed to connect to MySQL: " .
mysqli_connect_error(); }
// Make sure all of the input boxes have a value:
if (empty($fname)) { $error_msg[]='You forgot to enter your first name!'; }
if (empty($lname)) { $error_msg[]='You forgot to enter your last name!'; }
if (empty($uname)) { $error_msg[]='You forgot to choose a username!'; }
if (empty($pword)) { $error_msg[]='You forgot to choose a password!'; }
// Insert the data from the form into the DB:
if(count($error_msg)==0){
$sql = "INSERT INTO basic_information (First_Name, Last_Name,
Username, Password) VALUES ('$_POST[fname]', '$_POST[lname]',
'$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }
else { echo "Record has been added"; }
// Close the connection:
mysqli_close($con);
}else{
print_r($error_msg);
}
?>
Full working example to stop insertion of empty data
<?php
if (isset($_POST["submit"])) {
$emptyInput = NULL;
if (!($_POST["firstname"] == $emptyInput or $_POST["lastname"] == $emptyInput or $_POST["email"] == $emptyInput)) {
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('" . $_POST["firstname"] . "','" . $_POST["lastname"] . "','" . $_POST["email"] . "')";
if (mysqli_query($conn, $sql)) {
echo 'Record inserted successfully!';
}
} else {
echo 'all fields are compulsory!';
}
}
?>
You could use a $errors variable to hold the errors with all the fields
$error = array();//initializing the $error
if (empty($fname)) {
$error[] = 'You forgot to enter your first name!';
}
if (empty($lname)) {
$error[] = 'You forgot to enter your last name!';
}
if (empty($uname)) {
$error[] = 'You forgot to choose a username!';
}
if (empty($pword)) {
$error[] = 'You forgot to choose a password!';
}
if(!empty($error))//if error occured
{
die(implode('<br />', $error));//Stops the script and prints the errors if any occured
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);

change password in mysql table?

Hi im having a problem with my change password script. im trying to allow a user to change their password in the mysql table 'ptb_users.password' it's suppose to store this as md5.
When i hit submit in my form, i'm assuming it goes to changepassword.php but the page is just blank, nothing is echoed and im not getting any errors.
Can someone please show me where im going wrong with this, thanks
Here's my form:
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php");
require('includes/checks.php');
?>
<?php
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form method="post" action="includes/changepassword.php" name="form1" id="form1">
<input type="password" name="oldpassword" id="password" class="subject" placeholder="Old Password">
<input type="password" name="oldpassword" id="password" class="message" placeholder="Old Password">
<input type="password" name="newpassword" id="newpassword" class="message" placeholder="New Password">
<input type="image" src="assets/img/icons/loginarrow1.png" name="submit" id="submit" class="submit">
</form>
And here's my mysql function:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
?>
<?php
session_start();
include '_config/connection.php';
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']."");
if(!$result)
{
echo "The username you entered does not exist";
}
else
if($password!= mysql_result($result, 0))
{
echo "";
}
if($newpassword=$confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm new password fields must be the same";
}
?>
if(isset($_POST['submit']))
{
$email = $_POST['email'];
echo $newpassword = ($_POST['password1']);
echo $confirmpasssword = ($_POST['password2']);
if($newpassword=$confirmpassword)
{
echo $newpassword = md5($newpassword);
echo $result = mysql_query("UPDATE users SET password='$newpassword' WHERE email='$email' ");
}
if($result)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm password fields must be the same";
}
}
can anyone tell me is this correct coding, to change password and store in mysqldb.
first you do not check the old password properly (md5 stored, plaintext compare... won't work)
second you do not have any confirmpassword set, so this wont work too
what would work is:
$password = md5($_POST['password']);
$newpassword = md5($_POST['newpassword']);
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']." AND password = '".$password."'");
if(!$result)
{
echo "The username you entered does not exist or old password didn't match";
}
else
{
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
There are many things wrong with this.
Let's get the basics out of the way first:
Don't use mysql_ functions. switch to PDO or mysqli while you can.
md5 is in its dying days. See this answer - understandably, you may be so entrenched in md5 you can't get out without pestering every user to update their pw.
Your problem then is this:
if($password!= mysql_result($result, 0))
You're not comparing against a md5 stored hash. It should be something like this:
if(md5($password) != mysql_result($result, 0))
and this:
if($newpassword=$confirmnewpassword)
is just reassigning a variable. I think you wanted
if($newpassword == $confirmnewpassword)
As for output, you may want to consider the if/else structures you're using here. This could be cleaned up significantly and all together looks out of date. Maybe just an opinion.
If you have a specific thing to hone in on, let me know and I may update.
EDIT
This whole block should be cleaned. Something like this may help:
if(!$result)
{
echo "The username you entered does not exist";
}
else
{
if(md5($password) != mysql_result($result, 0))
{
echo "Current PW does not match what we have";
}
else
{
if($newpassword == $confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."") or die(mysql_error());
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
}
else
{
echo "The new password and confirm new password fields must be the same";
}
}
}

Categories