Mysqli check if username already exists [duplicate] - php

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
Yes I know this has been asked before and I literally copied code from multiple answers from this site trying to get it to work. This is the code I've been using now but it keeps allowing me to enter duplicate entries.
$query = mysqli_query($con, "SELECT * FROM Email WHERE Email = '".$testemail. "'");
if(mysqli_num_rows($query) > 0){
echo "Email is already in use.<br>";
}else{
$query = mysqli_query($con, "SELECT * FROM Username WHERE Username = '".$testname. "'");
if(mysqli_num_rows( $query) > 0){
echo "Username is already in use.<br>";
}else{
$sql = "INSERT INTO users (Username, Password, Email, Firstname, Lastname, Lastlogin, Registered) VALUES ('$testname', '$testpass', '$testemail', '$testfirstname' , '$testlastname', '$lastlogin', '$registered')";
if ($conn->query($sql) === TRUE) {
echo "New account created successfully<br>";
}
}
}
Is the specific code that should stop this from happening but here is the full page:
First time that I'm working with a login system like this so I wouldn't be surprised if I'm making some stupid mistake.
EDIT: I tried editing it but its still not working, I also made the 'Email' and 'Username' column unique in my database. But all this does is stop the data from being inputed at all. I also tried a workaround where it displays a error at error number 1062 but that happens hasn't worked yet.
The new code
I missed something obvious as well, I'm using a IF statement so it only loops through the fie query check once I think

I suspect those SELECT queries are failing because they're not reading the same data that's inserted into the database. Here's your insert:
INSERT INTO users ...
But you're selecting from different tables:
SELECT * FROM Email ...
SELECT * FROM Username ...
If the values are in a table called users, why are you selecting from tables called Email and Username? Maybe you meant to select from users instead? Which also means you can do it in one query instead of two:
SELECT * FROM users WHERE Username = '".$testname. "' OR Email = '".$testemail. "'

I made the name column UNIQUE within my database and than added new data through this line:
$sql = "INSERT INTO users (Username, Password) VALUES ('$testname', '$testpass')";
if (!($conn->query($sql))) {
echo "Username is already in use";
}else{
echo "New account created successfully";
}
If the entered data already exists it will give a error which than simply sends a message that the name is already in use.

Related

My form only adds one user, I can add another one when i delete the previous user in my database. Anyone has any tips? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I know my code looks bad, but I just started using PHP. I can't fix the problem and I have been looking online for hours.
$sql = "INSERT INTO user (username, pass) VALUES ('$username', '$pass')";
$sql_check = "SELECT * FROM user WHERE username = '$username'";
$res = $conn->query($sql);
$res_check = $conn->query($sql_check);
if ($res_check->num_rows > 0) {
$melding = "Gebruikersnaam is al in gebruik";
} else if($res) {
$melding = "Gebruiker geregistreerd";
} else {
$melding = "Gebruiker niet geregistreerd";
}
you should check if your table already has an unique AND auto incrementing index!
Explanation:
If you add an entry the database will give it an unique id (counting from 1).
But if the field is not set as "auto incrementing" the index will always be zero and therefore it will fail to add another entry.
In phpmyadmin:
go to "structure" and edit the field ID. Check "AI" (auto increment) and make sure that it is used as primary key (key symbol).
Try This$conn is mysql connection variable$username user name variable $pass is user password
user_signup($conn,$username,$pass);
// Call function
function user_signup($conn,$user_name,$password)
{
$sql_check = "SELECT * FROM user WHERE username = '$user_name'";
$res_check = $conn->query($sql_check);
if ($res_check->num_rows > 0) {
echo "Username already exists!";
} else{
$sql = "INSERT INTO user (username, pass) VALUES ('$user_name', '$password')";
$conn->query($sql);
echo "insert data successfully";
// you can redirect another page
}
}

Ensure username and email address are unique

I am trying to verify whether or not a username and email address exist in my database and have tried to do a if, elseif, else statement to no avail.
I want to first run a check to see if the username is fine - obviously if not, an echo statement will appear. If the username doesn't exist, run an elseif statement to see if the email address is unique - again if not, another echo statement will appear. For the final statement, if all other conditions return false, I want to run the below code so that the user's input is submitted to the database.
I initially tried to declare two variables with a statement to check if the username=$username and email_address=$email_address then check to see if the number of rows returned from a mysqli_query is more than 1 for the username. I entered an elseif statement with the same but for email address but then I had an else statement with the below code in {} brackets.
I have deleted the original code because too many errors were thrown up, and was probably too convoluted and messy when a more elegant way to do what I was exists.
Any help would be appreciated.
if(isset($_POST['submit']))
{
$sql = "INSERT INTO users (first_name, last_name, username, email_address, password, gender, city, country, verification_code, verified, sign_up_date) VALUES (
'$first_name',
'$last_name',
'$username',
'$email_address',
'$password',
'$gender',
'$city',
'$country',
'$verification_code',
'1',
'$sign_up_date')";
$result = mysqli_query($conn,$sql);
header("Location:confirmation.php");
}
What you want is an integrity check on the data. You should do this check inside the database. The simplest way is with unique constraints/indexes:
create unique index unq_users_username on users(username);
create unique index unq_users_email on users(email);
If you attempt to insert or update a row so it violates these constraints, then your data modification step will fail with an error.
You need to create an index for them.
Use The following command to create the index:
CREATE UNIQUE INDEX index_name ON table_name (column_name)
Check This Link for more info: https://www.w3schools.com/sql/sql_create_index.asp
You could write a function to check your database first for example:
$errors = []; // you can add errors to this array.
if (isset($_POST['submit']))
{
// first do your validation here against empty values and invalid email
$sql = "SELECT * from users where email='$email' and username='$username'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$errors[] = "Username and email has been taken.";
}
if (!empty($errors))
{
// loop through your errors and echo them
} else {
// insert your values into the database
}
}

How can I verify a form with an SQL databse?

So I have an SQL database that has a table for accounts and info, and another one for storing comments on articles. I Have a form for submitting comments and it works just fine, but I wanted to implement a feature to prevent spam and non registered accounts. I was trying to find a way to make the following code work so that it would call upon my account table and check to see if the username section matches what was entered in the form.
I want it to check through my username column on the table to see if what was entered in the box is actually in the database as well, that way if it hasn't been registered it won't submit.
My problem I keep running into is that I try this
<?
if ($_POST['Uname']==`username`){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
But when I do this it thinks that "username" is what the username needs to be in order to submit properly.
I do not want every username to need to be "username" in order for them to submit, I just want it to check through my username column to see if what was entered is one of the registered usernames in the SQL column.
Im not sure if this is possible, or if I am making any sense, but this is my first post on this site and I would appreciate any help I could get.
Full code is below
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("sql***.*******.com","*****","*******");
$db_selected = mysql_select_db("*********",$con); //My login
$test2=$_GET['ID']; //Ignore
$_POST['#']=$test2; //Ignore
$sql="Select * from `Articles` and `Accounts`"; //For pulling data
mysql_query($strSQL,$con);
if ( ? == ? ){ //What should go here?
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Edit
So after making the changes needed, should my previous code end up like this?
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("*******","********","*****");
$db_selected = mysql_select_db("*****",$con);
$test2=$_GET['ID'];
$_POST['#']=$test2;
$username = $_POST['Uname'];
$sql = "Select `id` from `Accounts` where `username` = $username";
mysqli_num_rows($sql,$result);
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
echo $result;
if ($row_cnt!=''){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES ('".$_POST['Uname']."',
'".$_POST['Comment']."',
'".$_POST['Date']."',
'".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Obviously what you doing is not correct, as of now you are putting condition as :
if ($_POST['Uname']==`username`)
which means you saying any user who's name is 'username' should be able to comment, but what you want to achieve is, any user who is valid user and is exist in db should be able to comment. So for that you should write a select sql to check the user, :
$username = $_POST['Uname'];
$sql = "select id from yourusertable where username = $username";
then,
perform
mysqli_num_rows
to check if you get anything greater than zero. If yes, then allow to submit comments.
Simply apply the check that only loggedIn user can comment. So if the user will not exist in users table it will not be loggedIn nor can comment.

Is is possible to do this with only one sql?

I want have an insert query, but before inserting I check whether the username and email are used by someone else. If used, I want to cancel insert query and echo a message to say whether username or email is in use.
Here my code:
$sql = "SELECT 1 FROM user WHERE username='".$_POST['username']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('This username is already exists');
$sql = "SELECT 2 FROM user WHERE email='".$_POST['email']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('This email address is already exists');
$sql = "insert into user (username,email,password,tel,type) values ('".$_POST['username']."','".$_POST['email']."','".$_POST['password']."','".$_POST['telnumber']."','member')";
if(!mysql_query($sql))
die(mysql_error());
I want these three sql statements in one. It can be either using cases or something else that you suggest. So,
Is it possible to zip this code into one sql query?
As a result what I need is
sql = "sql_query"
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row['result']==1)
die('This username is already exists');
else if($row['result']==2)
die('This email is already exists');
}
die('you have succesfully registered');
thanks for any advice.
While I suggest you follow #cularis' answer, you may be interested in the following alternative:
Give email and username the UNIQUE constraint, by creating a unique index for both of these.
run your INSERT query, and if this fails... (due to duplicate keys)
run the suggested combined SELECT, to determine which field existed (username or email)
You can combine the first two queries like this:
$sql = "SELECT * FROM user WHERE username='".$_POST['username']."' OR email='".$_POST['email']."'";
Have look at mysql_real_escape string to sanatize your input.
Assuming you don't care about a more specific error case you could probably just do the following:
$sql = "SELECT * FROM user WHERE username='".$_POST['username']."' OR email='".$_POST['email']."'";
if(!$result = mysql_query($sql))
die(mysql_error());
while($row = mysql_fetch_array($result))
die('The username or email address is already being used');
$sql = "insert into user (username,email,password,tel,type) values ('".$_POST['username']."','".$_POST['email']."','".$_POST['password']."','".$_POST['telnumber']."','member')";
if(!mysql_query($sql))
die(mysql_error());
This isn't the best of designs if you're looking for, as I said, specific error cases. So if you are okay with just telling the person there is an error that one or both are in use then that should work.
I am not sure as I am very rusty in PHP/MySQL but I assume that if such cases of both exist then multiple rows may be returned and I forget exactly how mysql_fetch_array works but I assume it's an array of all results valid for the query so you should be set. As long as the array exists, you know there was a hit in the db.

duplicate entries mysql and php

I have set my database fields "username" and "email" to unquie, when using the code below this only works if the "username" already exists, an error is then echoed. If they email exists the user gets a mysql duplicate error, when the same error as above should be shown.
<?php
require_once ( 'connection.php' );
$username=$_POST['username'];
$password=md5($_POST['password']);
$email=($_POST['email']);
$ip=$_SERVER['REMOTE_ADDR'];
session_start();
$query = "INSERT INTO users (username, password, email, rank, ip, active) VALUES ('$username','$password', '$email', '1', '$ip', '0')";
$sql = "SELECT username AND email FROM users WHERE username = '$username' AND email = '$email'" ;
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);
if ( $count== 0 )
{
if (!mysql_query($query))
{
die('Error: ' . mysql_error());
}
echo "You are signed up, please follow the link on your email to active your account.";
}
else
{
echo "Username or Email already exists"."<br>Try Again</br>";
}
?
Thanks
Try switching
WHERE username = '$username' AND email = '$email'"
to
WHERE username = '$username' OR email = '$email'"
Edit: I'm trying to guess what you're trying to do here. From your description, it seems you want either the username or the email to be unique and you have two separate unique indexes on those columns. Your code checks for the combination of username and email to be unique.
Edit 2: Also, I think you might want to look into the concepts of SQL Injection and Concurrency.
Switch to an OR clause in your WHERE statement instead of AND.
Also, DO NOT use the values given in $_POST (or $_GET and $_REQUEST for that matter) without making sure they are safe. What would happen if I sent a username with SQL in it?
','','','','',''); DELETE FROM users;
Make sure you using add_slashes() or a similar process to clean the data before sending to the database.

Categories