How to prevent username duplicates in mySQL (PHP) [duplicate] - php

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
This is how my users register for database, but my question is: How can I prevent the database from having copies of the same username, or in other words, how can I prompt to the user that "Your username already exists" if their username exists in the database.
<?php
$error = ""; // error
$GoodJob = "";
//When submit button is pressed, send data.
if(isset($_POST['submit'])){
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
$error = "<br>Please insert only letters or numbers.";
}else{
// Define username, firstname, lastname, email and password.
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Define database information
$hostnameV = "***";
$usernameV = "***";
$passwordV = "***";
$databaseV = "***";
//connection to the database
$connection = mysql_connect($hostnameV, $usernameV, $passwordV)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseV,$connection)
or die("Could not select company");
// To protect MySQL injection for Security purposes
$username = stripslashes($username);
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$email = stripslashes($email);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
// SQL query to send information of registerd users
# FORMULA: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
$query = mysql_query("INSERT INTO `company`.`users` (`id`, `username`, `firstname`, `lastname`, `email`, `password`)
VALUES (NULL, '$username', '$firstname', '$lastname', '$email', '$password')", $connection);
//close the connection
mysql_close($connection);
} // end if statement
***
}
?>
<div id="main">
<div id="login">
<h2>REGISTER</h2>
<form action="" method="post">
<input id="name" name="username" placeholder="Pick a username" type="text">
<input id="name" name="email" placeholder="Your email" type="text">
<input id="name" name="firstname" placeholder="firstname" type="text">
<input id="name" name="lastname" placeholder="lastname" type="text">
<input id="password" name="password" placeholder="Create a password" type="password">
<input name="submit" type="submit" value=" REGISTER ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>

I would first start by not using the mysql_* functions as they are deprecated and switch to PDO as it works correctly.
To answer your question, you should simply query the database for the username, if it exists, tell the user.
Before the Insert, using PDO and prepared statements.
$stmt = $dbh->prepare('SELECT count(*) FROM user WHERE username = ?');
$stmt->execute(array($username));
$res = $stmt->fetch(PDO::FETCH_NUM);
$exists = array_pop($res);
if ($exists > 0) {
// tell the user it already exists.
} else {
// carry on with your insert.
}
As others have suggested, making the username unique should also be done. I wouldn't write my code to fail though when trying to insert a duplicate username, I would still test if it exists.
So to provide a bit more clarity, in reference to the below comments about using exceptions, here's why I wouldn't write my code to throw an exception if someone enters a username that is already taken. Exceptions, in my opinion, should be exceptions. That means that something exceptional happened. Someone entering a username that is already taken, I consider that to be a normal operation of the application and it should be handled in a normal non-exceptional fashion. If however, someone entered a valid username and between the time that I checked that it was not taken and when I'm running my insert, someone else grabbed that username (in that 2 millisecond timeframe), that would be an exception and I would handle it. To the user, that "exception" would look exactly the same, but in my code it would be handled as an exception.
So that's why I wouldn't just write my code to do an insert that throws an exception when someone enters a username that is already taken. I would check whether it's taken or not and then insert it, throwing an exception if that username was snagged between the time I checked and when it was inserted. I think that's good application design and proper use of exceptions. Others can disagree, but that's how I would do it. Exceptions should be exceptional, not part of the normal course of doing business.

You can set a validation for checking the username is exist or not.
<?php
function checkUserExist($username){
$checkExist = "SELECT username from userTable WHERE username ='" . $username . "'" or die(mysql_error());
mysql_query($checkExist);
if($checkExist > 0){//That means username is existed from the table
return true;
}else{//username isn't exist
return false;
}
}
if(checkUserExist($username)){//function return true
echo "username is already exist, please change.";
}else{
//Insert the user info into db
}
This is an example for checking the username by using function with mysql_query, you can also use PDO to implement it, Cheers!

Related

PHP Error: Code always returning the same value

I've made this code to login in to a site, but my code always returns Onjuiste gegevens(incorrect data). I don't know why.
In my database I have made 1 account with username: sander and password: sander. When I enter this in the form I still get "Onjuiste gegevens". Could someone please help me to fix this?
<?php
$conn = mysqli_connect("localhost", "root", "", "login");
if (isset($_POST['inloggen'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND '$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 1) {
echo "Juiste gegevens!";
} else {
echo "Onjuiste gegevens!";
}
echo "<br />";
}
?>
<form method="post" action="">
<label>Username</label>
<input type="text" name="username"/><br />
<label>Password</label>
<input type="password" name="password"/><br />
<input type="submit" name="inloggen" value="Inloggen"/>
</form>
There's a problem with your query, you've missed out password, it should be:
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
Also, you should prevent MySQL Injection:
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
Read more about mysqli_real_escape_string() at http://www.w3schools.com/php/func_mysqli_real_escape_string.asp.
Also read up on MySQLi Prepared Statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php, it's a good way to prevent MySQL Injection.
Tip: Remember to store passwords hashed for security purposes. Do not store them as plain-text.
Your query is not valid. You're forgetting the password column in your database.
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
Besides having a wrong query, the query is open for sql injections.
Try this
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
which improves security by using mysqli_real_escape_string() for post variables.
mysqli_real_escape_string() -
Escapes special characters in a string for use in an SQL statement,
http://php.net/manual/en/mysqli.real-escape-string.php
Your query's logic is wrong, you forget password:
SELECT * FROM users WHERE username = '$username' AND password='$password'

Mysqli and PHP not sending data [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm building a recruiting website and need to save user data in my database but my form isn't sending anything to the database in phpmyadmin (using WAMP).
I checked the error logs for PHP, MySQL and Apache but don't see any errors. I also added "if/echo" blocks inside the $conn variables to test the connection, which returned true. Code below.
<!-- index.html-->
<form action="process.php" method="post">
<input type="text" name="first_name" placeholder="First Name" /><br/>
<input type="text" name="last_name" placeholder="Last Name" /><br/>
<button type="submit" name="submit"></button>
</form>
//database.php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "xxxx";
$dberror1 = "Could not connect to the database!";
$dberror2 = "Could not find selected table!";
// Connection to the database, Already tried this with echo statement and works
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
// Selecting the database to connect to
$select_db = mysqli_select_db($conn, 'mainbase') or die ($dberror2);
//process.php
<?php include 'database.php';
if(isset($_POST['submit'])) {
// Creating variables to store form values
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
//Executing the query
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name') //Values in 'candidates' table on phpmyadmin
VALUES ('$first_name','$last_name')");/*variables from above*/
}
You're using myqli incorrectly. But on top of that, use PDO to connect to your database instead. It's safer and easy to expand in the future. Here is an example of how to connect to your database with PDO.
<?php
$myUser = "XXXXXX";
$myPass = "XXXXXX";
try{
$dbPDO = new PDO('mysql:host=localhost;dbname=xxxxxxxx', $myUser, $myPass);
$dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection was successful";
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
?>
Simply change the Xs to your server's settings.
When you want to start a query simply you can do it like so:
$query = $dbPDO->prepare("SELECT * FROM Table_Name");
$query->execute();
Of course you'd want to pass variables to your queries so you can do that like this:
$query = $dbPDO->prepare("SELECT * FROM Table_Name WHERE ID = :id");
$query->bindParam(':id', $id);
$query->execute();
That keeps SQL injection off your worries. Just make sure to sanitize your variables before binding them to the query as well.
I figured I'd show how to insert your variables into your table with PDO.
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (:fname, :lname)");
$query->bindParam(':fname', $firstName);
$query->bindParam(':lname', $lastName);
$query->execute();
You could also make an array of both of your POST variables and pass that instead of binding each variable at a time.
$candidateName = array('$_POST['first_name']', '$_POST['last_name']');
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (?, ?)");
$query->execute($candidateName);
I hope that helps!
Happy coding!
The problem
Don't put table name and column names between apostrophes. That's what's causing your query to fail. Apostrophes are used to pass strings.
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name')
VALUES ('$first_name','$last_name')");
Should be
mysqli_query($conn, " INSERT INTO candidates(first_name, last_name)
VALUES ('$first_name','$last_name')");
Or
mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if you like it better.
The error handling
In order to verify the problem you can echo the mysqli_error() function result whenever the query fails, it's a nice practice and would probably have helped you find a solution faster than asking it here.
$query= mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if(!$query) //the query will return 0 if it fails
{
echo mysqli_error($conn);
}
The security issue
You're adding POST value directly into your query, which is dangerous.
On these lines:
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
You should be escaping user input.
This will escape any special characters that can cause issues in the mysql query.
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);

PHP MYSQL Prevent user or email inserted twice

I want to prevent if the user enters same email twice, which will create duplicate entry. Please help me to solve this small problem, I have searched stackoverflow for this problem but everyone has their own database with own method.
Thank you
<form action="create_subscriber.php" method="post">
<input placeholder="Name" name="inputName" type="name" required/>
<input name="inputEmail" placeholder="example#email.com" name="Submit" type="email" required/>
<input name="Submit" type="submit" value="Subscribe"/>
</form>
create_subscriber.php below
<?php
//include 'connection.php'
$dbhost = "localhost";
$dbuser = "sampleuser";
$dbpass = "samplepass";
$dbname = "sampledb";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$name = $_POST['inputName'];
$email = $_POST['inputEmail'];
if(!$_POST['Submit']){
echo "Please enter a name & email";
//header('Location: index.php');
}else{
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES(NULL,'$name', '$email' ) ")
or die(mysql_error());
echo "User has been added";
header('Location: success.php');
}
?>
Since you are not doing any validation, you can use the Email as a unique field and do an REPLACE query. http://dev.mysql.com/doc/refman/5.0/en/replace.html
I would strongly advise you to write validation in the form of a query check against the database prior to attempting to do a secondary insert. It's even made easy by persistent connections being available so you don't have the overhead of few ticks it takes to do that validation query.
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES (NULL,'$name', '$email' )
WHERE NOT EXISTS (
SELECT email FROM subscriptions WHERE email='$email'
)")
Simply execute a preliminary query to check for email uniqueness
SELECT * FROM subscriptions WHERE `email` = ?
(I wrote the query in the form of a prepared statement
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You should use prepared statement to inject values into queries).
If you get any row then the email is not unique so redirect to the original form page, possibly displaying an error message.
If you don't get any record then you may proceed with the insert and then render a "mail registration succeeded" page.
Btw: you can't echo something and then set a header. As you start sending output header can't be set/changed.

link database and stmt and prepare

I want to write a mysql php code
if I put the ID and passwd it will check with database
and link to the login success or login fail.
but my code it failed to go to the login success even though id and passwd is correct
$mysqli = new mysqli('localhost', 'root', '', 'project');
$username = $_POST['username'];
$password = $_POST['password'];
//to check whether the username exists or not
$stmt = $mysqli->stmt_init();
$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");
$stmt->bind_param('ss', $username, MD5($password));
$stmt->bind_result($result,$result2);
$stmt->execute();
Im not sure my prepare statement and the bind_param is in the right position.
it should compare the MD5(password) (encrypted) password with input password
**
if ($stmt->fetch())
{
session_start();
$_SESSION['pid'] = $username;//login id
header('Location: Login Successfully.php');
exit();
}else{
$_SESSION['pid'] = $username;
header('Location: Failed to login.php');
}
**
and this is my fetch. but it always go to the failed to login.php
this is my login.php before execute above code. it get the input id and passwd and pass it to the fetch code.
Login:
Enter your username and password below:
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
When using prepare(), you need to use placeholders ? instead of the actual variables. Also it looks like passwd should be password. So you will want to change
$stmt->prepare("select pid, password from person where pid = '$username' and passwd = '$password'");
to
$stmt->prepare("select pid, password from person where pid = ? and password = ?");

PHP use mySQL to check existing username [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have been following this tutorial for building a simple registration / login script.
http://forum.codecall.net/topic/69771-creating-a-simple-yet-secured-loginregistration-with-php5/
I am new with PHP, but I have a lot of experience using C++, so I thought the transitions wouldn't be too hard, I just need to figure out the syntax. I also did a very very quick introduction to mySQL at university, so I thought it would be a lot easier to use mySQL to check for an existing username when the user has registered, though my knowledge isn't too good. I thought something like this would work;
SELECT username
FROM codecalltut
WHERE username = username;
Would this actually work? It is selecting the username from the database codecalltut and then it checks to see if the username being inputted is already a username? Even if this is correct I don't know how to include it in my PHP.
I've tried using
$qry = "SELECT username
FROM codecalltut
WHERE username = username;"
But I just get a syntax error when it moves to the next statement.
<?php
$qry = "SELECT username
FROM codecalltut
WHERE username = username;"
//if register button was clicked.
} else {
$usr = new Users; //create new instance of the class Users
$usr->storeFormValues( $_POST ); //store form values
//if the entered password is match with the confirm password then register him
if( $_POST['password'] == $_POST['conpassword'] ) {
echo $usr->register($_POST);
} else {
//if not then say that he must enter the same password to the confirm box.
echo "Password and Confirm password not match";
}
}
?>
This is the query used to construct the database:
CREATE DATABASE `codecalltut` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `codecalltut`;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varbinary(250) NOT NULL,
PRIMARY KEY (`userID`,`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
This is the HTML code for when the user clicks "Register"
<li class="buttons">
<input type="submit" name="register" value="Register" />
<input type="button" name="cancel" value="Cancel" onclick="location.href='index.php'" />
</li>
Your HTML form for Registration
<form action='' method='POST'>
<input type='text' name='username' />
<input type='password' name='password' />
<input type='password' name='re-password' />
<input type='submit' name='submit' />
</form>
Your PHP code
if($_POST){
if(empty($_POST['username']) && empty($_POST['password']) && empty($_POST['re-password'])) {
echo 'Please enter all fields';
}else {
$username = $_POST['username'];
$password = $_POST['password'];
$re_password = $_POST['re-password'];
if($password !== $re_password){
echo 'Both passwords do not match';
}else {
$db_name =
$db_user =
$db_pass =
$conn = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx',
array( PDO::ATTR_PERSISTENT => true )
);
$stmt = $conn->prepare("SELECT username,password FROM users WHERE username = ? AND password = ?");
$stmt->execute(array($username, $password));
if($stmt->rowCount() === 0 ) {
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->execute(array($username, $password));
if($stmt->rowCount() ===1){
echo 'Registration complete';
}else {
echo 'Sorry, unknown error: please try again later';
}
}else {
echo 'Sorry, the username '.$username.' already exists';
}
}
}
}
Did you omit the part where you execute the query? All I see is that you're assigning the query to a variable but not executing it.
I see that you're using PDO, so you should NOT concatenate the username you're checking for into the query, as it leaves you open to SQL injection. I'm assuming your database object is called "$con" and your table is codecalltut. Do this:
$qry = "SELECT * FROM codecalltut WHERE username=?";
$stmt = $con->prepare($qry);
$stmt->execute(array($_POST['username']));
$exists = ($stmt->rowCount() === 1) ? true : false;
Remove the last ; :
$qry = "SELECT username
FROM codecalltut
WHERE username = username;";
REMOVE THIS --^ ^----ADD THIS
Followed by what #Nelson said. You should also enclose strings in your query with ' single quotes like this:
$qry = "SELECT username FROM codecalltut WHERE username = 'username' ";
Also, if you are writting inside, any table, row names, which might conflict with the database language itself, make sure to enclose them with backticks (`)
bytheway
A simple login script would work out this way. (hope, you are using PDO or mysqli instead of mysql functions to interact with your database
// set isset(), to validate if form is submited and then
$username = $_POST['username'];
$pass= $_POST['pass'];
Now, the code.
$conn = new PDO('mysql:host=localhost; dbname=***;', 'db-user', 'user-pass');
$stmt = $conn->prepare("SELECT username,password from members WHERE username = ? AND password = ?");
$stmt->execute(array($username, $password));
if($stmt->rowCount() === 1){
echo 'welcome'.$username;
}else {
echo $username.' is not found'
}

Categories