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);
}
?>