Editing user profile: How to avoid user from entering duplicate values? - php

I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?

You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.

Related

Update a row in database while retaining the previous data in other columns if their input is blank

I have a form where the user can update a student by entering the username of the student. But if the user only wants to update the firstname and leaves the lastname blank, this will remove the last name from the mysql database.
html form:
<form class="" action="updateStudent.php" method="post">
Username: <input type="text" name="username" value="">
Firstname: <input type="text" name="firstname" value="">
Lastname: <input type="text" name="lastname" value="">
<input type="submit" name="" value="Update">
</form>
php:
<?php
include('connection.php');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$sql = "update employee set firstname = '$firstname',
lastname = '$lastname',
where username = '$username'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}
else{
echo "error: $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
how can I change my code so when the user only wants to change the first name and leave the last name, it wont end up empty in the database?
Add this line your form
<input type="text" name="lastname" value="<?php echo $lastname; ?>" />
$lastname is the last name from the resultset. The condition is that you should query the record before rendering the page.
Use COALESCE:
UPDATE `employee`
SET `firstname` = COALESCE($firstname, firstname),
`lastname` = COALESCE($lastname, lastname),
`username` = COALESCE($username, username)
WHERE `username`= '$username'
And leave the value="" out of the HTML form in the input tags.
Same thing i put in the comment,
U need to check if the person only changed it's first name
U could do this
include('connection.php');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
/**
* instead of checking if the input is an empty string, try to set a minimum
* length for the string lets put it on 5
*/
$minLength= 5;
$sql = '';
if(strlen($lastname) > $minLength && strlen($firstname) > $minLength){
//both have the required length
$sql = "update employee
set firstname = '$firstname',
lastname = '$lastname',
where username = '$username'";
} else if(strlen($firstname) > $minLength) {
//only first name with required length
$sql = "update employee
set firstname= '$firstname',
where username = '$username'";
} else if (strlen($lastname) > $minLength) {
//only lastname with required length
$sql = "update employee
set lastname= '$lastname',
where username = '$username'";
} else {
//none applied
$sql = false;
}
if($sql){
//it's "true" if it contains something
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "error: $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
}
But i strongly recomment if u are updating information, in the update form by default those field get the current values when the form is loaded.
I assume you mean that if someone leaves the input form fields empty, you want to NOT update that column.
To do this, build a dynamic query.
<?php
include 'connection.php';
$username = $_POST['username'];
$sql = "UPDATE employee SET ";
//where username = '$username'";
$countColumns = 0; // track how many columns we are going to update
$columns = ['firstname', 'lastname']; // add more columns to this list if needed.
foreach($columns as $key ) {
if ( ! empty($_POST[$key] ) {
$value = $_POST[$key];
if ( $countColumns > 0 ) $sql .= ',';
$sql .= " `{$key}` = '{$value}'";
$countColumns++;
}
}
if ( $countColumns > 0 ) {
$sql .= " WHERE username = '{$username}'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}
else {
echo "error: $sql. " . mysqli_error($conn);
}
}
else {
// Nothing to update
}
mysqli_close($conn);
Use prepared statements with MySQLi, they are much safer and will help you prevent an SQL injection attack!
To solve your problem you can simply check which values came in empty and set a proper query, like this:
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
// check if all fields came in and if username is not empty
if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['firstname']) && isset($_POST['lastname']))
{
// you can use strlen($_POST['firstname']) > 2 to check if it at least has 2 characters
if(!empty($_POST['firstname']) && empty($_POST['lastname']))
{
$sql = $conn->prepare("UPDATE employee SET firstname = ? WHERE username = ?";
$sql->bind_param("ss", $_POST['firstname'], $_POST['username']);
}
else if(empty($_POST['firstname']) && !empty($_POST['lastname']))
{
$sql = $conn->prepare("UPDATE employee SET lastname = ? WHERE username = ?";
$sql->bind_param("ss", $_POST['lastname'], $_POST['username']);
}
else if(!empty($_POST['firstname']) && !empty($_POST['lastname']))
{
$sql = $conn->prepare("UPDATE employee SET firstname = ?, lastname = ? WHERE username = ?";
$sql->bind_param("sss", $_POST['firstname'], $_POST['lastname'], $_POST['username']);
}
if ($sql->execute())
{
echo "Record updated successfully";
}
else
{
echo "error: " . mysqli_error($conn);
}
$sql->close();
}
$conn->close();
?>
This should work regardless of which they want to update, or if they want to update both. Though I'm not sure if you'd have to escape the single quote inside the strings within the IF statements or not.
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$flen = strlen($firstname);
$llen = strlen($lastname);
$c = $flen + $llen;
if ($flen>0) {
$fname = "firstname = '$firstname'" ;
}
if ($c=2) {
$com = "," ;
}
if ($llen>0) {
$lname = "lastname = '$lastname'" ;
}
$sql = "update employee set " . $fname . $com . $lname . "
where username = '$username' ";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}
else{
echo "error: $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
I recently created a form where I needed to make sure that all fields were filled out, so I used the following code to ensure that all fields were filled out before continuing with my sql query. Probably not the cleanest, but it prevents empty fields. That way nothing will be left blank and it will update accordingly.
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$flen = strlen($firstName);
$llen = strlen($lastName);
switch ($flen) {
case 0:
echo "Click Back button and please make sure to fill in all fields";
exit;
}
switch ($llen) {
case 0:
echo "Click Back button and please make sure to fill in all fields";
exit;
}

PHP login code error with mysql_query()

I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>

What do I have to do to my code so it will only create the account if the email doesn't already exist in the Database? [duplicate]

This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 8 years ago.
<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
while ($myrow = mysql_fetch_array($result)) {
if ($email == $myrow['email']) {
$errorMessage = "Account with that email already exists";
} else {
$errorMessage = "Email doesn't match!";
}
}
if ($_POST['submit']) {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}
?>
When I fill in the form and hit submit it just inserts into the database even though the emails are the same. I tried putting the if statement with the submit button into the while loop but that didn't work either.
Use mysql_num_rows function to check weather the user already exist on the database or not. Use the code below
<?php
$errorMessage = "";
// start the session and register the session variables
session_start("ProtectVariables");
// get the command value (use request since both post and get are used
$firstname = $_POST['firstNameZ'];
$lastname = $_POST['lastNameZ'];
$password = $_POST['passwordZ'];
$email = $_POST['emailZ'];
$sql = "SELECT email FROM account WHERE email='" . $email . "'";
$result = mysql_query($sql,$db);
if(mysql_num_rows($result)==0){
if ($_POST['submit']) {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}
}
else
{
echo "the user with this email address already exist";
}
?>
Hope this helps you
You could change your condition to check whether or not the error message has been filled:
if ($_POST['submit'] && $errorMessage == "Email doesn't match") {
$sql_insert = "INSERT INTO account (firstname,lastname,password,email) VALUES ('$firstname','$lastname','$password','$email')";
$result_insert = mysql_query($sql_insert,$db);
}

registration form not not showing validation error

I am having issues getting the error to appear when a user is entering a user name that is already taken.
In the code below the database is updated when successful entry is made. However, when an entry is made with a duplicate user name, the entry is placed in the database and no error message is shown. I have looked on the net and tried a few methods and this what I have so far. Thank you for taking a look :)
<?php
// Create connection
$con = mysqli_connect('172.16.254.111', "user", "password", "database"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} //sql syntax below, first line is collumn titles on the db and second line is values from the html document
//$_post is a form of sending information in php
{
$username = strip_tags($_POST['username']);
$password = md5(strip_tags($_POST['pass']));
$password2 = md5(strip_tags($_POST['pass2']));
$fullname = strip_tags($_POST['fullname']);
$email = strip_tags($_POST['email']);
$department = strip_tags($_POST['department']);
if ($password != $password2) //password doestn equal same as password 2 then the message below is displayed (working)
{
echo "<H2>password doesn't match</H2>";
}
$usercheck = "SELECT * FROM Users WHERE username=$username";
$usercheck2 = mysql_query($usercheck);
if (mysql_fetch_assoc($usercheck2)) {
echo "<H2>This username already exists, please pick another</H2>";
} else {
$sql = "INSERT INTO Users(username, password, password2, email, fullname, department)
VALUES('$username','$password','$password2','$email','$fullname','$department')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<H2>Registration was successful, please use the access console above</H2>";
}
}
?>
Excuse any comments in the code; I am a beginner at PHP and coding in general.
You're missing some quotes. Try this:
$usercheck = "SELECT * FROM Users WHERE username = '$username'";
// ----------------------------------was missing---^---------^
$usercheck2 = mysql_query($usercheck);
if (mysql_num_rows($usercheck2)) {
echo 'user exists';
}
Also, you shouldn't be using the mysql_* functions. Look into using PDO
Change $usercheck = "SELECT * FROM Users WHERE username=$username";
for this $usercheck = "SELECT * FROM Users WHERE username='$username'"; And tell me if it works.

null values submitted to mysql database

I am trying to make a user system for my website but having some trouble with submitting it. It always submit a 0 to the database for everything. I have read on w3schools about global and local variables and I think this may be my problem but I don't know for sure.
Heres my code
<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];
if(!isset($firstname) || !isset($lastname) || !isset($username) || !isset($password) || !isset($passwordconf) || !isset($email) || !isset($securityq) || !isset($qanswer))
{
echo "You did not fill out the required fields.";
}
$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0)
{
echo "The username you entered is already taken";
}
$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
{
echo "The email you entered is already registered";
}
if($password != $passwordconf)
{
echo "The passwords you entered do not match";
}
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}
else
{
$salt = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
$hpassword = crypt($password,$salt);
$insert = "INSERT INTO users (firstname, lastname, username, password, email, securityq, qanswer, salt)
VALUES ('$firstname','$lastname','$username','$hpassword','$email','$securityq','$qanswer','$salt')";
mysql_query($insert);
if(!mysql_query($insert))
{
die('Could not submit');
}
else
{
echo "Information was submited. Please check your email for confirmation";
}
}
?>
Let me try to answer.
First of all, I agree with advice to move to PDO. mysql_* functions are deprecated. But if you wish to use it, escape every variable directly before sql due to '-symbols in your sql:
$hpassword = mysql_real_escape_string($hpassword );
As for me, the following syntax is easier to view rather than insert ... values():
$insert = "INSERT INTO `users`
SET `firstname` = '$firstname',
SET `hpassword` = '$hpassword'..."
Actually, I am trying to forgot this kind of code. I use PDO or comfortable uniDB class for simple apps.
Is it correct behaviour that it inserts user no matter errors like matching password? You should fix conditions.
Your conditions logic is wrong. You submit after if(!preg_match($regex, $email)). So if email is correct, it submits. Fix it as follows using ELSEIF
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(mysql_num_rows($emailquery) > 0){
echo "The email you entered is already registered";
}elseif($password != $passwordconf){
echo "The passwords you entered do not match";
}elseif(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}else{
// insertion code HERE
}

Categories