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."}
Related
I have the following code to connect between mysql database and android.
$conn = mysqli_connect($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message causing the error
if ($conn) {
$response["Connection"] = 1;
}
else {
$response["Connection"] = 0;
}
$userID= $_POST['user_id'];
function recordExists() {
$query = "SELECT * FROM user_table";
$result = mysqli_query($conn, $query);
$response["found"] = "i am here";
while($row=mysqli_fetch_array($result)){
$response["found"] = $row['user_id'];
if($row['user_id']==$userID){
return true;
}
}
return false;
// $result_num_rows = mysqli_num_rows($result);
//
// if($result_num_rows>0) {
// return true; // The record(s) do exist
// }
// return false; // No record found
}
$exists=recordExists();
if ($exists) {
$query = "SELECT * FROM user_table WHERE $userID";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array ($result);
$Nickname = array();
if ($row['nickname'] == NULL){
array_push($response["nickname"], "False");
}else{
array_push($response["nickname"], $row["nickname"]);
}
$response["Sync"] = "Already Added";
echo (json_encode($response));
} else {
$UserToBeAdded= $_POST['user_id'];
$NameToBeAdded= $_POST['name'];
$EmailToBeAdded= $_POST['email'];
$UserToBeAdded2 = mysqli_real_escape_string($conn, $UserToBeAdded);
$NameToBeAdded2 = mysqli_real_escape_string($conn, $NameToBeAdded);
$EmailToBeAdded2 = mysqli_real_escape_string($conn, $EmailToBeAdded);
$sql_query = "insert into user_table (user_id, name, email) values ('$UserToBeAdded2', '$NameToBeAdded2', '$EmailToBeAdded2');";
mysqli_query($conn, $sql_query);
$response["ID"] = $UserToBeAdded2;
$response["Name"] = $NameToBeAdded2;
$response["Email"] = $EmailToBeAdded2;
$response["Sync"] = "Just Added";
$response["nickname"] = "False";
echo (json_encode($response));
}
mysqli_close($conn);
from the above code, i can receive responses from the php side. however the following response is not received.
$response["found"] = "i am here";
if u see from my code above, basically the function recordExists() will definitely be called. however the response " i am here" is not encoded in JSON when i emulate the android app. anything wrong?
try to declare the response variable above all functions. so add $response=array();on top of the file.
here you can read up about the scope of php variables:
https://secure.php.net/manual/en/language.variables.scope.php
You have a variable scope issue with the connection variable. Pass the connection variable as a parameter.
recordExists($conn);
Also use prepared statements to prevent sql injection attacks.
I am developing a login and registration application in android studio by looking at some of video tutorials,and the php scripts are 100% as in the tutorial and it was working at first time, then now its not working.I can't identify what's gone wrong.. I am new to php and android
In the tutorial it's purely working.
Tutorial link >>Registration app tutorial
spent more than two days for linking database, still stucked over, finally into stackoverflow, Hope for good Solution or Guidance. Thanks
init.php which is for Connection, and connection Success
<?php
$host = "localhost";
$user = "blood";
$password = "rifkan123";
$dbname = "userdb";
$con = mysqli_connect($host,$user,$password,$dbname);
if(!$con)
{
die("Error in Database Connection".mysqli_connect_error());
}
else
{
Echo "<h3> Database Connection Success !";
}
?>
login.php Script for login
<?php
$email = $_POST["email"];
$pass = $_POST["password"];
require "init.php";
$query = "Select * userinfo where email like. '".$email."';";
$result = mysqli_query($con,$query);
if(mysqli_num_rows($result)>0)
{
$response = array();
$code ="login_true";
$row = mysqli_fetch_array($result);
$name = $row[0];
$message ="Login Success ! Welcome ".$name;
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array(server_response=>$response));
}
else
{
$response = array();
$code ="login_false";
$message ="Login Failed ! Try Again";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array(server_response=>$response));
}
mysqli_close($con);
?>
register.php for user registration
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$pass = $_POST["password"];
require "init.php";
$query = "select * from userinfo where email like '".$email."';";
$result = mysqli_query($con,$query);
if(mysqli_num_rows($result)>0)
{
$response = array();
$code = "reg_false";
$message = "User Already Exist !";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
$query = "insert into userinfo values('".$name."','".$email."','".$pass."');";
$result = mysqli_query($con,$query);
if(!$result)
{
$response = array();
$code = "reg_false";
$message = "Registration Failed, Try Again!";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else
{
$response = array();
$code = "reg_true";
$message = "Registration Success, Login to Continue!";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
mysqli_close($con);
}
?>
I have missed the FROM in login script and after adding it new error detected
Screen shot new Error
You forgot FROM clause in login.php
Here
$query = "Select * from userinfo where email like. '".$email."';";
Also consider to add %% with like
<?php
$server_host = "host";
$server_username = "username";
$server_password = "password";
$server_dbName = "data base name";
$player_username = $_POST ["usernamePost"];
$player_password = $_POST ["passwordPost"];
$player_displayName = $_POST ["displayNamePost"];
$conn = new mysqli ($server_host, $server_username, $server_password, $server_dbName);
if (!$conn) {
echo "Error connecting to the server.";
}
$query_code = "SELECT Username FROM users WHERE Username = '{$_POST[usernamePost]}'";
$result_login = mysqli_query ($conn,$query_code);
$anything_found = mysqli_num_rows ($result_login);
if ($anything_found > 0) {
echo "An account with this username or display name already exsists, please choose another.";
}
if ($anything_found <= 0) {
$sql = "INSERT INTO users (Username, Password, Display_Name)
VALUES ('".$player_username."','".$player_password."','".$player_displayName."')";
$result = mysqli_query ($conn,$sql);
if ($result) {
echo "You may now login.";
}
if (!$result) {
echo "Error.";
}
}
?>
I'm using the Unity Engine to display the echoed result, does this script seem that it will echo "An account with this username or display name already exsists, please choose another." if there is already a username with the username entered? Also, would it echo "You may now login." if the account was created?
I made this script myself, I'm new to this PHP stuff. I'd appreciate it if someone looked this code over and explained to me why this isn't working.
The logic is wrong. Conditional statements are hanging dangerously :-)
Use this
<?php
$server_host = "host";
$server_username = "username";
$server_password = "password";
$server_dbName = "data base name";
$player_username = $_POST ["usernamePost"];
$player_password = $_POST ["passwordPost"];
$player_displayName = $_POST ["displayNamePost"];
$conn = new mysqli ($server_host, $server_username, $server_password, $server_dbName);
if (!$conn) {
echo "Error connecting to the server.";
}
else{
$query_code = "SELECT Username FROM users WHERE Username = '{$_POST[usernamePost]}'";
$result_login = mysqli_query ($conn,$query_code);
$anything_found = mysqli_num_rows ($result_login);
if ($anything_found > 0) {
echo "An account with this username or display name already exsists, please choose another.";
}
elseif ($anything_found <= 0) {
$sql = "INSERT INTO users (Username, Password, Display_Name)
VALUES ('".$player_username."','".$player_password."','".$player_displayName."')";
$result = mysqli_query ($conn,$sql);
if ($result) {
echo "You may now login.";
}
else{
echo "Error.";
}
}
}
?>
The following always echoes 'success' even if mname is not found. If it's not found, it should show 'failed'. Why is it showing 'success' when I enter an mname that isn't found?
<?php
$conn = mysqli_connect("localhost","root","","lpdb");
//update
if (isset($_POST['forgot'])){
$password = 'password';
$mname = $_POST['mname'];
$query = "UPDATE logindb SET password ='$mname' WHERE mname = '$mname'";
$result = mysqli_query($conn, $query);
if ($result) {
echo 'success';
} else {
echo 'failed';
}
}
?>
From the documentation:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
An update that doesn't update anything isn't a failure, so the result is TRUE. Use mysqli_affected_rows to find out how many rows were updated by the UPDATE:
<?php
$conn = mysqli_connect("localhost","root","","lpdb");
//update
if (isset($_POST['forgot'])){
$password = 'password';
$mname = $_POST['mname'];
$query = "UPDATE logindb SET password ='$mname' WHERE mname = '$mname'";
mysqli_query($conn, $query); // ***
$result = mysqli_affected_rows($conn); // ***
if ($result > 0) { // *** Or perhaps == 1, up to you
echo 'success';
} else {
echo 'failed';
}
}
?>
firstcheck for mname:
<?php
//check if user submitted first
if (isset($_POST['forgot'])){
$password = 'password';
$mname = $_POST['mname'];
$conn = mysqli_connect("localhost","root","","lpdb");
//update
$query = "UPDATE logindb SET password ='$mname' WHERE mname = '$mname'";
$result = mysqli_query($conn, $query);
if($result){
echo 'success';
} else {
echo 'failed to update for some reason';
//or maybe echo the db err
echo mysqli_error();
}
?
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();
}