duplicate entries mysql and php - 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.

Related

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.

Register form PHP

I am a beginner in PHP & MySQL, I am trying to create this register form for a project I am working on currently, here is the PHP script, btw.. If there is a lot of mistakes, it is because I have just started!
The problem I am having is that it does not check the database if the email or username match, because if it did, it should reject.
PHP code:
<?php
//register php
error_reporting(0);
$regUsername = $_POST['reg-username'];
$regEmail = $_POST['reg-email'];
$regPassword = $_POST['reg-password'];
if(isset($regUsername) && isset($regEmail) && isset($regPassword)){
$connect = mysql_connect('localhost', 'root', '');
$selectDB = mysql_select_db('supermazad');
$query = mysql_query("INSERT INTO users (username, email, password) VALUES ('$regUsername', '$regEmail', '$regPassword')");
$checkIfSame = mysql_query("SELECT * FROM users WHERE username AND email LIKE '$query' ");
echo '<h1 class="successMessage">You have successfully registered!</h1>';
}
if($regUsername || $regEmail == $checkIfSame){
echo '<h1 class="errorMessage">The username or e-mail already exists.</h1>';
}
?>
You are trying to check if the username and email already exist in the database after inserting the username and email into the database. You should check beforehand either via a select with the username and email provided in the registraton, or by placing a unique key constraint on username and email fields.
Please use mysqli instead of mysql because it's safer
remove error_reporting(0)
don't use "like" because it might have many result
syntax error on the mysql query
try this one just debug if there are error but I think this works
$regUsername = $_POST['reg-username'];
$regEmail = $_POST['reg-email'];
$regPassword = $_POST['reg-password'];
if(isset($regUsername) && isset($regEmail) && isset($regPassword)){
$mysqli = mysqli_connect("localhost","root","","supermazad") or die("Error " . mysqli_error($mysqli));
$queryInsert = "INSERT INTO users (username, email, password)
VALUES
('$regUsername', '$regEmail', '$regPassword')";
mysqli_query($mysqli, $queryInsert); //this will insert the data from db
$queryUser = "SELECT username,email FROM users WHERE username = '$regUsername' AND email = '$regEmail'"; // this will authenticate and uses an exact match
$result = $mysqli->query($queryUser);
$row = mysqli_fetch_array($result);
echo '<h1 class="successMessage">You have successfully registered!</h1>';
}
if($regUsername == $row['username'] && $regEmail == $row['email']){ //this check if email and username are match with database $row['username'] store username from mysql field and $row['email'] do the same
echo '<h1 class="errorMessage">The username or e-mail already exists.</h1>';
}
by the way this is normal for a beginner but please improve your coding in the near future, make it cleaner and organize
I think you should do it like this after $selectDB = mysql_select_db('supermazad');:
$checkIfSame = mysql_query("SELECT * FROM users WHERE username LIKE '".$regUsername."' OR email LIKE '".$regEmail."' ");
if (mysql_num_rows($checkIfSame ) > 0) {
echo '<h1 class="errorMessage">The username or e-mail already exists.</h1>';
} else {
//insert new user here
$query = mysql_query("INSERT INTO users (username, email, password) VALUES ('$regUsername', '$regEmail', '$regPassword')");
}
Also, you have this in your post :
if the email or username match
so you should be using OR, not AND
Try this:
$checkIfSame = mysql_query("SELECT * FROM users WHERE username LIKE '".$regUsername."' OR email LIKE '".$regEmail."' ");
if (mysql_num_rows($checkIfSame ) > 0) {
echo '<h1 class="errorMessage">The username or e-mail already exists.</h1>';
} else {
//insert new user here
$query = mysql_query("INSERT INTO users (username, email, password) VALUES ('$regUsername', '$regEmail', '$regPassword')");
}

Mysqli check if username already exists [duplicate]

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.

Checking if a username or email exists in the DB already

I want to check if the username of email already exists in the DB when a user signs up to my website.
I have the following code which isn't working and i'm not sure why. If anyone could point me in the right direction to validate against already existing info in the DB I would greatly appreciate it! Thanks
$query = mysql_query("
SELECT *
FROM users
WHERE username = '". $username ."'
OR email = '". $email ."'"
);
if (mysql_num_rows($query) > 0){
die ('Username or email already in use.');
}
This can be done by changing the username field as a primary key or unique.
Or run the sql
SELECT username FROM table WHERE username='$php_username_var';
Please look at the following code, this is being used on the sign up page of my site, I hope you get your answer.
$sq="SELECT * FROM users WHERE username='$username' and password='$password'";
$rsult=mysql_query($sq); $count=mysql_num_rows ($rsult);
if($count==1){echo "username already in use"; }
else
{
$sql="INSERT INTO $tbl_name(username, password, sex, place)
VALUES('$username', '$password', '$sex', '$place')"; }
$result=mysql_query($sql); if($result)
{header("location:home.php"); }
else
{ echo "Error, please go back and sign up again! "; } ?>

Categories