How do I check database for a value that already exists? - php

I am currently building a signup script for my website. I new to the whole PHP-mySQL interaction bit. Anyway, this is the code I've gotten so far. The problem is that I had added some more code to check if the username already exists in the database, after the form submits it kicks to store.viddir.com/join/signup.php rather than store.viddir.com/login, like I had it. Any pros that can help a novice out? Many thanks
<?php
$submitted = $_POST["submitted"];
if($submitted == 'yes') {
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userName = $_POST["userName"];
$password = $_POST["password"];
$confirmPassword = $_POST["confirmPassword"];
$eMail = $_POST["eMail"];
// Kill script if input fields are blank
if ($firstName == '' or $lastName == '' or $userName == '' or $password == '' or $confirmPassword == '' or $eMail == '')
{
die();
}
// Check if passwords match
if ($password != $confirmPassword)
{
die();
}
// Check if password is appropriat length
$passwordLength = strlen($password);
if ($passwordLength < 7 or $passwordLength >30) {
die();
}
/////////////////////////
// Connect to database //
/////////////////////////
$sqlserver = "localhost";
$sqluser = "XXXX";
$sqlpassword = "XXXXXX";
mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
mysql_select_db("store");
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT userName FROM userInfo WHERE userName = '$newUserName'");
if ($checkUserName) {
die();
}
//////////////////////////
// Insert into database //
//////////////////////////
// Signup time in Unix Epoch
$time = time();
// Human readable date
$date = date("F jS, Y g:i:s A");
$sql = "INSERT into userInfo (firstName, lastName, userName, password, eMail, time, date) VALUES ('$firstName', '$lastName', '$userName', '$password', '$eMail', '$time', '$date')";
//$sqlserver = "localhost";
//$sqluser = "XXXX";
//$sqlpassword = "XXXXXX";
//mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
//mysql_select_db("store");
mysql_query($sql) or die(mysql_error());
mysql_close();
header("Location: http://store.viddir.com/login");
exit;
}
?>

See mysql_num_rows. You should also look into using PDO or MySQLi
http://php.net/manual/en/function.mysql-num-rows.php
if (mysql_num_rows($query) > 0) {
echo "user already exists";
}

You should do a count in the mysql query and then check if the result is not equal to 0.
Example:
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT COUNT(userName) FROM userInfo WHERE userName = '$newUserName'");
if ( mysql_result($checkUserName, 0, 0) != 0 ) {
die();
}

Related

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

Encrypt password login issue

I am using below code to encrypt user registration password during registration. But the problem is that I can't get login with same password again, I might be because password in DB is different and encrypted and not same as the password user enter.
<?php
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($firstname) && !empty($lastname) && !empty($username) && !empty($email) && !empty($password)) {
$firstname = mysqli_real_escape_string($db_connect, $firstname);
$lastname = mysqli_real_escape_string($db_connect, $lastname);
$username = mysqli_real_escape_string($db_connect, $username);
$email = mysqli_real_escape_string($db_connect, $email);
$password = mysqli_real_escape_string($db_connect, $password);
$sql = "SELECT randsalt FROM user ";
$select_randsalt_query = mysqli_query($db_connect, $sql);
if(!$select_randsalt_query) {
die("Query failed".mysqli_error($db_connect));
}
while($row = mysqli_fetch_array($select_randsalt_query)) {
$salt = $row['randsalt'];
///crypt function takes 2 parameter. one from DB
///and other from user input.
// $password = crypt($password, $salt);
}
$sql_register ="INSERT INTO user(user_firstname, user_lastname, username, user_email, user_password, user_role )";
$sql_register .="VALUES('{$firstname}', '{$lastname}', '{$username}', '{$email}', '{$password}', 'Unknown' ) ";
$query_register = mysqli_query($db_connect, $sql_register);
if(!$query_register) {
die("Query failed".mysqli_error($db_connect));
}
$message = "<h3>Your Registration has been Submitted</h3>";
} else {
$message = "<h3>You Can't leave field Empty</h3>";
}
} else {
$message = '';
}
?>
I tried to do something like this in login.php
<?php
if(isset($_POST['submit'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
//To prevent SQL injection and store into new variable
$Username = mysqli_real_escape_string($db_connect, $Username);
$Password = mysqli_real_escape_string($db_connect, $Password);
$sql_login = "SELECT * FROM user WHERE username = '{$Username}' ";
$query_login = mysqli_query($db_connect, $sql_login);
if(!$query_login){
die("Query Failed".mysqli_error($db_connect));
}
while($row = mysqli_fetch_assoc($query_login)){
$username = $row['username'];
$user_password = $row['user_password'];
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_email = $row['user_email'];
$user_role = $row['user_role'];
}
$Password = crypt($Password, $user_password);
///User validation
if( ($Username === $username && $Password === $user_password) && $user_role === "Admin"){
//Using session to store information from db
//Using session from right to left. Right is the variable got from db.
$_SESSION['USERNAME'] = $username;
$_SESSION['PASSWORD'] = $user_password ;
$_SESSION['FIRSTNAME'] = $user_firstname;
$_SESSION['LASTNAME'] = $user_lastname;
$_SESSION['EMAIL'] = $user_email;
$_SESSION['ROLE'] = $user_role;
header("Location: ../admin/index.php");
}else{
header("Location: ../index.php");
}
}
?>
but this is not working. Sorry people I just entered to the PHP world and don't have deep understanding.
Welcome to PHP development. Let me make your life a lot easier:
Regardless of what your tutorial/book/friend said, don't escape strings, use prepared statements instead. They're a lot easier to implement safely and your life becomes a heck of a lot easier. (If you rely on escaping, and you remember to escape 2999 out of 3000 parameters a user can control, you're still vulnerable.)
Instead of mucking about with crypt(), just use password_hash() and password_verify().
There are updated guides everywhere that can explain how to use these features better, but http://www.phptherightway.com is the one the community points to the most.

Checking against if statement giving wrong result?

Here is the code
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$phone = $_POST['phone'];
$referral = $_POST['refer'];
$referred = false;
mysql_connect("localhost","username","password") or die (mysql_error());
mysql_select_db("database") or die ("Cannot connect to database");
$query = mysql_query("Select * from member");
while($row = mysql_fetch_array($query))
{
$table_users = $row['username'];
$table_email = $row['email'];
$table_phone = $row['phone'];
if($referral == $table_users)
{
$referred = true;
}
if($username == $table_users || $email == $table_email || $phone == $table_phone)
{
$bool = false;
}
}
if(($bool))
{
$username = mysql_real_escape_string($username);
mysql_query("INSERT INTO member (username, password, email, phone, refer) VALUES ('$username', '$password', '$email', '$phone', '$referral')");
if($referred)
{
$from="Sent from test";
$subject="New user referred.";
$message="A new user " . $username . " has been referred by " . $referral . "Please stay updated. ";
mail("mymail", $subject, $message, $from);
}
$_SESSION['login'] = true;
echo "Thank you for registering with us.You can login now to start earning.";
}
If the referral code field is left empty or it does not match any value in database it still sends
the mail. So, what is going on here? I have added some more code. I left a part of it earlier.
This statement if($referral == $table_users) doesn't look right. You have not set the $referral variable anywhere in your code.

Login suddenly stopped working

I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories