This my PHP code and I used mobile_number as primary key and I want to insert new users from an Android app where there's no duplicate users based on mobile_number.
<?php
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$link = mysqli_connect("localhost", "root", "", "blood");
$response = array()
if ( isset($_POST['frist_name'])&& isset($_POST['last_name'])&&isset($_POST['gendar']) &&isset($_POST['don_date'])&&isset($_POST['birth_date'])&& isset($_POST['blood'])&&isset($_POST['mobile_number']) && isset($_POST['pass']) && isset($_POST['email']))
{
$frist_name = $_POST['frist_name'];
$last_name = $_POST['last_name'];
$gendar = $_POST['gendar'];
$don_date = $_POST['don_date'];
$birth_date = $_POST['birth_date'];
$blood=$_POST['blood'];
$mobile_number = $_POST['mobile_number'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$result = mysqli_query($link,"Insert into login(frist_name,last_name,gendar,don_date,birth_date,blood,mobile_number,pass,email,latitude,longitutde,address) values('$frist_name','$last_name','$gendar','$don_date','$birth_date','$blood','$mobile_number','$pass','$email','0','0','not iserted')");
if ($result)
{
$response["success"] = 1;
$response["message"] = "Registration successfully.";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
You can user PHP's mysqli_error & mysqli_errno immediately after calling mysql_query() function. These functions include detail about error & error number by the latest operation with database. Saying in code:
if ($result)
{
$response["success"] = 1;
$response["message"] = "Registration successfully.";
$response["errno"] = mysqli_errno($link);
$response["error"] = mysqli_error($link);
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
$response["errno"] = mysqli_errno($link);
$response["error"] = mysqli_error($link);
echo json_encode($response);
}
JUST MAKE SURE not to run any operation against database between the mysqli_query() & the above section
Then with error & errno in hand, you can make the users aware of the fact that someone has been registered using their mobile number.
when db prevent user from registertion this mean user alredy registered :]
else
{
$response["success"] = 0;
$response["message"] = "an user alredy registered";//this is solution
echo json_encode($response);
}
You may try alter your mobile number column in database with unique constraint. So that, when there's duplicate mobile number, the db won't allow you to insert the data and it returns error.
Below is the description about SQL unique constraint. Hope this helps.
SQL UNIQUE Constraint
Related
I'm retrieving users from my database with this php code below.
The problem is that when I execute the query without the AND condition, it works fine. With the AND condition it gives me always the else result.
include("config.php");
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$contact = mysqli_real_escape_string($con, $_GET['contact']);
$password = mysqli_real_escape_string($con, $_GET['motdepasse']);
$sql = "SELECT * FROM bonfoodUtilisateurs WHERE contact = '$contact' AND motdepasse = '$password'";
$result = mysqli_query($con,$sql);
$response = array();
if (mysqli_num_rows($result)!=0) {
$response['code'] = '1';
$response['message'] = 'success message.';
echo json_encode($response);
mysqli_close($con);
}else{
$response['code'] = '2';
$response['message'] = 'error message.';
echo json_encode($response);
mysqli_close($con);
}
?>
I'm expecting to get a result like ```{"code":"2","message":"error message."}
if the user's ```contact and ```password don't exist in the data table
otherwise get ```{"code":"1","message":"success message."}
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
Im trying to make a login php for an android app, I modified this php from a tutorial, the issue is I used to always get a response of "success" = 0 "message"= "Not all fields are filled", so I added a few print_r to see where is the problem now I only get this result aimatosnintendo , with are the inputs for username and password, so it's not even getting to the ifs, this is my code:
<?php
// array for JSON response
$response = array();
define('DB_USER', ""); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', ""); // database name
define('DB_SERVER', ""); // db server
// array for JSON response
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE);
// check for post data
print_r ($_POST['username']);
print_r ($_POST['password']);
if(isset($_POST['username'],$_POST['password'])) {
$username = $_POST["username"];
$password = $_POST["password"];
$sql = "SELECT *FROM login WHERE username = $username AND password = $password";
$result = $conn->query($sql) or die (mysqli_connect_error());
print_r ($username);
if (!empty($result)) {
// check for empty result
if (mysqli_num_rows($result) > 0) {
$result = mysqli_fetch_array($result);
$loginfo = array();
$loginfo["name"] = $result["name"];
$loginfo["username"] = $result["username"];
$loginfo["password"] = $result["password"];
$loginfo["phone"] = $result["phone"];
$loginfo["email"] = $result["email"];
$loginfo["license"] = $result["license"];
//$loginfo["expiration"] = $result["expiration"];
// success
$response["success"] = 1;
// user node
$response["logina"] = array();
array_push($response["logina"], $loginfo);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "Wronglogin";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "Wronglogin";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Not all fields are filled";
// echoing JSON response
echo json_encode($response);
}
?>
db user password server and name are all correct i just deleted them in this post for safety, i have a code to register info on the database and it works but this one gets me stuck
im expecting a $response["success"] = 1; when username and password match with the database
Try
$sql = "SELECT * FROM login WHERE username = '". $username ."' AND password = '".$password."'";
I have written simple PHP code to register user details from my iphone app. and it works fine and return JSON output. i have added that code below
header('Content-type: application/json');
include 'connection.php';
$response = array();
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if($username == NULL || $password == NULL || $email == NULL ){
$response["success"] = 0;
$response["message"] = "Something Empty";
}else{
$sql = "INSERT INTO User (username, password, email)
VALUES ('".$username."', '".$password."', '".$email."')";
if ($conn->query($sql) === TRUE) {
$response["success"] = 1;
$response["message"] = "Done";
} else {
$response["success"] = 0;
$response["message"] = "Error";
}
}
echo json_encode($response);
$conn->close();
but when i try to check username already exists before adding to the tables. im getting error saying from my Xcode Log.
JSON text did not start with array or object and option to allow fragments not set.
if($username == NULL || $password == NULL || $email == NULL ){
$response["success"] = 0;
$response["message"] = "Something Empty";
}else{
$query = mysql_query("SELECT * FROM User WHERE username='".$username."'");
if (mysql_num_rows($query) != 0)
{
$response["success"] = 0;
$response["message"] = "Username Already Exists";
}else{
$response["success"] = 1;
$response["message"] = "That Name Fine";
}
}
It is most likely a php error (potentially only a notification or warning depending on your error_reporting settings) that is polluting the json output.
You'll need to debug the problem and you may consider the error_reporting level for production.
I want to receive json data from android side.
The android side is sending username and password in json to this php side.
This is my php code:
public function actionGetUserLogin()
{
// array for JSON response
$response = array();
$conn=mysqli_connect("localhost","root","","db");
$user_login = "select * from user" ;
$query = mysqli_query ($conn, $user_login);
while($results = mysqli_fetch_array ($query)){
$user_name = $results['mobile_user_name'];
$pass = $results['mobile_user_pass'];
echo $user_name;
echo "</br>";
echo $pass;
echo "</br>";
}
//compare the POST data from user with the existing username and password in database table
if($_POST['username']==$user_name&&$_POST['username']!=""&&$_POST['password']==$pass&&$_POST['password']!="")
{
//if match with database record
$response["success"] = 1;
$response["message"] = "correct";
}else{
$response["success"] = 0;
$response["message"] = "wrong";
}
echo json_encode($response);
Yii::app()->end();
}
I get an error when i test out this method using this url: http://localhost/myproject/index.php/user/getuserlogin
The error is : Undefined index: username
Is it something gone wrong with my php when accepting the json?
Is there a way to display the json data that was sent by android?
public function actionGetUserLogin()
{
Add this check before creating db connection
if(!isset($_POST['username'],$_POST['password']) || strlen($_POST['password'])*strlen($_POST['username'])==0){
header($_SERVER['SERVER_PROTOCOL']. ' 401 Unauthorized');
return false;
}
// array for JSON response
$response = array();
I suggest you to implement datasource connection as singleton
$conn=mysqli_connect("localhost","root","","db");
$user_login = "select * from user" ;
$query = mysqli_query ($conn, $user_login);
while($results = mysqli_fetch_array ($query)){
$user_name = $results['mobile_user_name'];
$pass = $results['mobile_user_pass'];
echo $user_name;
echo "</br>";
echo $pass;
echo "</br>";
}
//compare the POST data from user with the existing username and password in database table
if($_POST['username']==$user_name&&$_POST['username']!=""&&$_POST['password']==$pass&&$_POST['password']!="")
{
//if match with database record
$response["success"] = 1;
$response["message"] = "correct";
}else{
$response["success"] = 0;
$response["message"] = "wrong";
}
echo json_encode($response);
Yii::app()->end();
}
i am creating android application that need connection with php mysql the application work perfect in the android side.
the problem is in the php file when i am trying to store $_SESSION for id from file to file to file the php display an error :
Undefined variable id in c:\wamp\www\android_connect\status.php on line 53
how can i fix this error i will post the three file of php that contain
register
login
status
register.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
if(empty($_POST['user']) || empty($_POST['password'])){
$response["success"] = 0;
$response["message"] = "enter Both Fields";
// echoing JSON response
die (json_encode($response));
}
// check for required fields
else if (isset($_POST['user']) && isset($_POST['password']) ) {
$user = $_POST['user'];
$password = $_POST['password'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
//check if the user exist !!!!
$check = mysql_query("SELECT * FROM users WHERE user = '$user'");
$count_query = mysql_num_rows($check);
if($count_query > 0){
$response["success"] = 0;
$response["message"] = "User Already Exist!!";
// echoing JSON response
die (json_encode($response));
}else if(strlen($user)<6){
$response["success"] = 0;
$response["message"] = "Your user Name Must bigger than 6 Char.";
// echoing JSON response
die (json_encode($response));
}else if(strlen($password)<8){
$response["success"] = 0;
$response["message"] = "Your Password Must bigger than 8 Char.";
// echoing JSON response
die (json_encode($response));
}else{
// mysql inserting a new row
$result = mysql_query("INSERT INTO users(user, password) VALUES('$user', '$password')");
//**************************
//added and can be deleted
//*************************
$id = mysql_insert_id();
// check if row inserted or not
if ($result) {
// successfully inserted into database
//**************************
//added and can be deleted
//*************************
$_SESSION['id'] = mysql_insert_id();
$response["success"] = 1;
$response["message"] = "User successfully created.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
die (json_encode($response));
}
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
die (json_encode($response));
}
?>
login.php
<?php
ob_start();
#session_start();
//array for JSON response
$response = array();
// check for required fields
if(empty($_POST['user']) || empty($_POST['password'])){
$response["success"] = 0;
$response["message"] = "enter Both Fields";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['user']) && isset($_POST['password']) ) {
$user = $_POST['user'];
$password = $_POST['password'];
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$sql = mysql_query("Select * from users where user='$user' and password = '$password'")or die(mysql_error());
$count_query = mysql_num_rows($sql);
if($count_query >0){
//*******************************
//added can be deleted
//*******************************
$user_details = mysql_fetch_array($sql);
$response["success"] = 1;
$id = $user_details['id'];
$_SESSION['id'] = $id;
$response['id'] = $user_details['id'];
$response["message"] = "correct Informations";
// echoing JSON response
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "Wrong User Or Pass";
// echoing JSON response
echo json_encode($response);
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
ob_end_flush();
?>
status.php
<?php ob_start();
//array for JSON response
$response = array();
if(!isset($_SESSION)) { session_start();
}
if(isset($_SESSION['id'])) {
$id= $_SESSION['id'];
}
//var_dump ($id);
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for required fields
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "Your Text Field is empty";
// echoing JSON response
die (json_encode($response));
} else if (isset($_POST['status'])) {
$status = $_POST['status'];
$sql = mysql_query("INSERT INTO status (status_text, uid)VALUES('$status', '$id')")or die(mysql_error());
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Status Saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Error in saving the status.";
// echoing JSON response
die (json_encode($response));
}
}
ob_end_flush(); ?>
i know that the error is in the insert query but i do not know why it do not assign the sesion id to the variable $id.
You need to start the Session in status.php first, I'm pretty sure in register.php you need to do the same thing.