Updating password mysqli in PHP if a new one is entered - php

I'm a little new to PHP and mysqli and don't think I'm going around this the right way; maybe I need to check if it's the same, and if not update the password? I'm not sure how to do this though.
At the moment on the user edit form I'm not passing the current password value, but I can pass it and it will pass as md5 format.
PHP
// user information
$getID = $_POST['id']; // id
$name = $_POST['name']; // name
$username = $_POST['username']; // username
$email = $_POST['email']; // email
$phone = $_POST['phone']; // phone
$password = md5($_POST['password']); // password
if($password == ''){
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?
WHERE id = ?
";
} else {
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?,
password =?
WHERE id = ?
";
}
/* Prepare statement */
$stmt = $mysqli->prepare($query);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
if($password == ''){
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'ssss',
$name,$username,$email,$getID
);
} else {
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'sssss',
$name,$username,$email,$password,$getID
);
}

You did one mistake in your code.do not use MD5 before checking blank password . MD5 also encrypt blank value so $password == '' condition always wrong.
// user information
$getID = $_POST['id']; // id
$name = $_POST['name']; // name
$username = $_POST['username']; // username
$email = $_POST['email']; // email
$phone = $_POST['phone']; // phone
/// do not use md5 here so condition get false always
$password = $_POST['password']; // password
if($password == ''){
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?
WHERE id = ?
";
} else {
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?,
password =?
WHERE id = ?
";
}
/* Prepare statement */
$stmt = $mysqli->prepare($query);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
if($password == ''){
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'ssss',
$name,$username,$email,$getID
);
} else {
$password = md5($password);
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'sssss',
$name,$username,$email,$password,$getID
);
}

Related

Inserting data in diferent tables

Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>

HTML PHP - How to check if the username already existed

The script is already working fine but I want to insert a command that allows only if the username is not yet used.
if (isset($_POST['submit'])) {
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
$position = htmlentities($_POST['position'], ENT_QUOTES);
$username = htmlentities($_POST['username'], ENT_QUOTES);
$password = htmlentities($_POST['password_two'], ENT_QUOTES);
$uniqid = uniqid('', true);
if ( $firstname == '' || $lastname == '' || $position == '' || $username == '' || $password == '') {
$error = 'ERROR: Please fill in all required fields!';
renderForm($error, $firstname, $lastname, $position, $username, $password);
} else {
if ($stmt = $connection->prepare("INSERT INTO employee (uniqid, firstname, lastname, position, username, password) VALUES (?, ?, ?, ?, ?, ?)")) {
$stmt->bind_param("ssssss", $uniqid, $firstname, $lastname, $position, $username, $password);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: Could not prepare SQL statement.";
}
header("Location: regemployee.php");
}
} else {
renderForm();
}
Make username unique on the DB, then when you try to insert the same username in to the DB again, the insert will through an error.
Alternatively you could do a SELECT * FROM employee WHERE username = ? and check if results is > 0.
Then you would know it exists already.
Do another SELECT query which checks if the submitted username already exist:
$stmt = $connection->prepare("SELECT * FROM employee WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
Then get the number of results:
$stmt->store_result();
$noofres = $stmt->num_rows;
$stmt->close();
Then, create a condition that if it yet doesn't exist, it will do the insert query:
if($noofres == 0){
/* INSERT QUERY HERE */
} else {
echo 'Username already taken.';
}

Check if already a user then insert into the database php

My code works, if I wish to insert into the database, but my checking whether the user already exists doesn't work.
*I thought the idea was to check if a row exists already with that username, if so don't add that user to the database, else
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$result = mysqli_query($mysqli, "SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1){
echo'User exists';
}else{
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}
You have mixed the Procedural style & Object oriented style for executing the query.
When using,
1) Procedural Style
$result = mysqli_query($mysqli, "Your Query");
use this, $row_count = mysqli_num_rows($result);
2)Object oriented style
$result = $mysqli->query("Your Query");
Use this, $row_count = $result->num_rows;
So, According to your code, You are using Object Oriented Style. So, you need to change
$result = mysqli_query($mysqli,"SELECT username FROM users WHERE username = '$username'");
to
$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");
Edited Code.
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$result = $mysqli->query("SELECT username FROM users WHERE username = '$username'");
$row_count = $result->num_rows;
if($row_count == 1)
{
echo 'User exists';
}
else
{
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute())
{
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}
else
{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}
For more info, check this mysqli_num_rows vs ->num_rows
$db = ("SELECT username FROM userlist WHERE username='$username'");
$query = $conn->query($db);
if(mysqli_fetch_array($query) > 0 ) { //check if there is already an entry for that username
echo "Username already exists!";
}

Registration System PHP, mysqli ( Hashing ) [duplicate]

This question already has answers here:
Where to put password_verify in login script?
(2 answers)
Closed 7 years ago.
Below is a simple registration script using php, I obviously want to store peoples data securely. I was wondering where would be the best place to implement the hashing script? Would it be implemented in the script below or have it alone?
<?php
//values to be inserted in database table
//session_start();
include('connect.php');
$email = $_POST['email'];
$password= $_POST['password'];
$username= $_POST['username'];
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
Another thing, when fetching peoples information from the database so they can sign in do I fetch their hashed password or do I have to recreate a hashed version of the password they've entered? I've read different ways of doing it, I just want to know the most secure. Thank you
EDIT:
This is my login code
<?php
include 'connect.php';
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $mysqli->prepare('SELECT password FROM users WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($password);
$stmt->fetch();
// Account exists, now we verify the password.
if (password_verify($_POST['password'], $password)) {
// Verification success! User has loggedin!
echo 'You have logged in!';
} else {
echo 'Incorrect username and/or password!';
}
} else {
echo 'Incorrect username blar password!';
}
$stmt->close();
} else {
echo 'Could not prepare statement!';
}
?>
ANSWER:
<?php
//values to be inserted in database table
//session_start();
include('connect.php');
//Fixed cost of 10 to fit server req
//Random salt to be added to the pass
$options = [
'cost' => 10,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$email = $_POST['email'];
$password= password_hash($_POST['password'], PASSWORD_BCRYPT, $options);
$username= $_POST['username'];
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>
While putting Users value into the variable is the perfect time to sanitize
It would be great if you use a Global function to sanitize data and use that function everywhere
Here is an Example of secure code (without OOP ):
<?php
// create a globa function
//
function string_sanitize($value) {
$search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
$replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
return str_replace($search, $replace, $value);
}
function sanitize($value){
return $this->string_sanitize(htmlentities(trim($value)));
}
//values to be inserted in database table
//session_start();
include('connect.php');
$email = sanitize($_POST['email']);
$username = sanitize($_POST['username']);
// Sanitize password using hash()
$password = hash('sha256', $_POST['password']);
$query = "INSERT INTO users (username, email, password) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('sss', $username, $email, $password);
if($statement->execute()){
print 'Success! ID of last inserted record is : ' .$statement->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
?>

PHP - Convert my deprecated MySQL to MySQLi

I'm a beginner here and i am learning the basic in converting from MySQL to MySQLi. I am currently working on this registration page which I would want to convert to the new MySQLi. Please advise me how to modify this script, I would prefer the procedural style.
UPDATE - The MySQLi coding is not working because it would insert into the database like the MySQL coding would, would appreciate if your can help me.
MYSQL
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysql_real_escape_string($_POST['name']);
$name2 = mysql_real_escape_string($_POST['name2']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email2 = mysql_real_escape_string($_POST['email2']);
$address = mysql_real_escape_string($_POST['address']);
$address2 = mysql_real_escape_string($_POST['address2']);
$address3 = mysql_real_escape_string($_POST['address3']);
$address4 = mysql_real_escape_string($_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysql_connect("localhost", "root", "Passw0rd") or die("Connection Error");
//select database
mysql_select_db("logindb") or die("Selection Error");
//namecheck
$namecheck = mysql_query("SELECT * FROM users WHERE email='{$email}'");
$count = mysql_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysql_query("INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysql_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
MYSQLI (NOT WORKING)
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysqli_real_escape_string($connect, $_POST['name']);
$name2 = mysqli_real_escape_string($connect, $_POST['name2']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$password2 = mysqli_real_escape_string($connect, $_POST['password2']);
$email2 = mysqli_real_escape_string($connect, $_POST['email2']);
$address = mysqli_real_escape_string($connect, $_POST['address']);
$address2 = mysqli_real_escape_string($connect, $_POST['address2']);
$address3 = mysqli_real_escape_string($connect, $_POST['address3']);
$address4 = mysqli_real_escape_string($connect, $_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die("Connection Error");
//namecheck
$namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'");
$count = mysqli_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysqli_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
Converting to mysqli is not about adding i to the old library.
The main difference is that mysqli offers prepared statement feature.
This saves you from the tedious task of manually escaping values with mysqli_real_escape_string.
The proper way to do it is to prepare your query:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = mysqli_prepare($connect, $query)) {
mysqli_stmt_bind_param($stmt,'sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/*Count the rows*/
if( mysqli_stmt_num_rows($stmt) > 0){
echo"New Record has id = ".mysqli_stmt_insert_id($stmt);
}else{
printf("Errormessage: %s\n", mysqli_error($connect));
die();
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
In addition to prepared statement, another advantage is the coding style, mysqli introduces OOP style, here is the same code in that style:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = $connect->prepare($query)) {
$stmt->bind_param('sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute query */
$stmt->execute();
/*Count the rows*/
if($stmt->num_rows > 0){
echo"New Record has id = ".$connect->insert_id;
}else{
var_dump($connect->error);
die();
}
/* close statement */
$stmt->close();
}
/* close connection */
$connect->close();
Both would achive the same. Good luck
I noticed one error in your script (mysqli script):
Instead of
$count = mysql_num_rows($namecheck);
do
$count = mysqli_num_rows($namecheck);
You can also check for errors in your query, like this (from w3schools - http://www.w3schools.com/php/func_mysqli_error.asp):
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
{
echo("Error description: " . mysqli_error($con));
}
Also try to do some debugging (echo some results) in your script to find errors.
Pass connection parameter inside
$lastid = mysqli_insert_id();
like
$lastid = mysqli_insert_id($connect);

Categories