Jump to content

PHP file to register user into database after checking if user already exists or not


Danielle999
Go to solution Solved by kicken,

Recommended Posts

I am new to PHP so I am not sure how to do this, but I want to create a PHP file that will register a user into a database.


It should first check if the mobileNo entered is already in the database. If it is there, then nothing will be added. If it isn't there, then the user will be added to the database.


I tried the following but it only works when the mobileNo isn't in the database and it successfully inserts the user in the database. BUT If the mobileNo entered already exists in the database, I receive the JSON response: {"message":"error.","success":0}



<?php

$response = array();

if (isset($_POST['name']) && $_POST['password'] && $_POST['mobile'] ) {

$name = $_POST['name'];
$password = $_POST['password'];
$mobile= $_POST['mobile'];

require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();

$result = mysql_query("SELECT mobile FROM users WHERE mobile= '$mobile' ");

if (!$result) {
die('Query failed to execute for some reason');
}

if (mysql_num_rows($result) == 0) {

$result2 = mysql_query("INSERT INTO users(username, password , mobile)
VALUES('$name' , '$password' , '$mobile' )");

if($result2)
{
$response["success"] = 1;
$response["message"] = "User successfully registered.";

echo json_encode($response);
}

else {

$response["success"] = 0;
$response["message"] = "error";
echo json_encode($response);

}
}

else {

$response["success"] = 0;
$response["message"] = "error.";
echo json_encode($response);
}
}
else {

$response["success"] = 0;
$response["message"] = "missing field";
echo json_encode($response);
}

?>

Link to comment
Share on other sites

  • Solution

Given that your code is using the mysql_* functions, I am going to assume you are actually using MySQL and not Microsoft SQL Server which is the forum where you posted this question.

 

First things first, you need to know that the mysql_* functions are old, deprecated, and slated for removal in some upcoming PHP version. You should forget these functions exist and switch to using either PDO (Recommended) or mysqli. PHP: The Right Way has some information about using PDO and there is also a good PDO Tutorial for MySQL Developers provided by the freenode ##php folks.

 

Secondly, if you want to ensure that the mobile number does not exist before inserting it, you need to handle this by creating a UNIQUE constraint on that column in the database. Then you will simply attempt to insert the value and see if it fails with a constraint violation. The code (using PDO with exceptions) would look something like this:

 

$username = 'example';
$password = 'example';
$mobile = '123456789';
try {
    $stmt = $db->prepare('INSERT INTO users(username,password,mobile) VALUES (?,?,?)');
    $stmt->execute([$username, $password, $mobile]);
    echo 'Data inserted successfully';
}
catch (PDOException $ex){
    if ($ex->getCode() == 23000){ //Check if it's a duplicate key violation.
        echo 'Mobile must be unique';
    }
    else {
        throw $ex;  //Rethrow other errors
    }
}
You'll want to make sure you normalize your mobile numbers so that someone inserting the same number but with different spacing/separation is correctly caught by the system as a duplicate. For phone numbers I store them in a VARCHAR column with all non-digit/letter characters removed.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.