2

I'm new in php and mysql. I'm trying to check if the user is already taken or not. If it's taken then it won't added to the database. However, I tried a lot of code to do this trick but none of the code I used worked. I'm not sure what I'm doing wrong. This what I have right now:

<?php

include 'db_settings.php';

db_connect();

//Escape variables for security
$user = mysqli_real_escape_string($con, $_POST['user']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO users (user, pass, email)
        VALUES ('$user','$pass', '$email')";


if (!mysqli_query($con,$sql)) {
    die('Error: ' . mysqli_error($con));
}

echo "1 record added</br>";

mysqli_close($con);

echo "<a href='sign-up.html'>sing-up again!</a></br>";
echo "<a href='index.html'> Go Back Home </a>";

?>`

I know this code don't have the checking function for the user if already taken or not because I deleted all the codes about it. So if it's possible if you could guys help me I will appreciate it.

dragon3002
  • 131
  • 2
  • 4
  • 14

4 Answers4

1

Your code seems to be fine do one thing run the below code on your mysql console or phpMyadmin

ALTER TABLE  `users` ADD UNIQUE (
`user`
);
manuyd
  • 201
  • 1
  • 8
0

You need to match the results from database with Select query and conditions in the where clause depends on what basis you want to match records. So you can try something like this

$query = "SELECT email,user FROM users where user='$user' and email='$email' ";   
$result = mysql_query($query);    
if (mysql_num_rows($result)) {    // user already exists   }    
else {     // Insert query    }
New Coder
  • 873
  • 8
  • 14
-1

You need to execute a select query first which will fetch the user with the posted email/username and check whether any record appear in the result or not.

Only after that fire the insert query.

$sql = "SELECT email FROM users where email='".$email."'";
$result = mysqli_query($con, $sql);

if (mysqli_num_rows($result) > 0) {
  //user already exists
}

There is one more alternate if you do not want to do any action in case of duplicate records.

Use INSERT...IGNORE it will not insert record on duplication.

Community
  • 1
  • 1
Bhavya Shaktawat
  • 2,504
  • 1
  • 13
  • 11
-1

You should try something like this.

<?php
include "db_setting.php";
 $user = $_POST['user'];
 $pass = $_POST['pass'];
 $email = $_POST['email'];

$check = mysql_query("select * from registration_table where username = $user");
$check_user = mysql_num_row($check);

if($check_user > 0)
{
echo "This username already exists";
}else
{

mysql_query("insert INTO registration_table ('user','pass','email') VALUES ($user,$pass,$email)");
}
AbhimanuSharma
  • 453
  • 1
  • 8
  • 21