2015-09-14 125 views
-1

我有以下登录脚本。用PHP登录脚本的JSON响应

<?php 

include("connect.php"); 
include("functions.php"); 
$error = ""; 

$j = new stdClass(); 
$j->status = "success"; 
$j->message = "Logged In"; 

if(isset($_POST['submit'])){ 


    $email = mysqli_real_escape_string($con,$_POST['email']); 
    $password = mysqli_real_escape_string($con,$_POST['password']); 

    if(email_exists($email,$con)){ 
     $error = "Email Exists"; 

     echo json_encode($j); 
    }else{ 
     $error = "Email does not exist"; 


    } 

} 

?>

的functions.php文件是。

<?php 
function email_exists($email,$con){ 


    $result = mysqli_query($con,"SELECT id FROM users WHERE email='$email'"); 

    if(mysqli_num_rows($result) == 1){ 
     return true; 
    }else{ 
     return false; 
    } 
} 

?>

什么我做的是从数据库中选择的ID和检查电子邮件与

mysqli_num_rows(query) 

函数存在。如果它返回一个或是真的,那么电子邮件存在,所以用户可以登录。如果不是意味着我们返回0或false,那么电子邮件不存在,因此用户不能登录。

我想返回每个案例一个JSON响应。例如,如果用户的电子邮件被找到然后。

{ 
    "status":"success" 
    "message:"You are now logged in" 
} 

当用户的电子邮件没有找到,那么,

{ 
    "status":"fail" 
    "message:"email not found" 
} 

任何想法?我创建了以下变量,但仅用于成功案例。我希望在发现没有电子邮件时将相同变量更改为失败

$j = new stdClass(); 
$j->status = "success"; 
$j->message = "Logged In"; 

谢谢。

+1

你有json_encode数组,而不是一个对象,函数是一个创建对象的客户端 –

+0

为什么送?它也适用于对象;) – l0rkaY

回答

0

试试这个:

$qry ='SELECT * FROM `registration` WHERE `email`="'.$email.'" && `password`="'.$password.'"'; 
$login = mysqli_query($con, $qry) or die (mysqli_error()); 
$no_of_row=mysqli_num_rows($login); 
$row1 = mysqli_fetch_assoc($login);  
    if($no_of_row==1) 
{ 
    $response["error"] = 0; 
    $response["success"] = 1; 
    $response["email"] = $email; 
    $response["message"] = "You Logged In Successfully"; 


} 
echo json_encode($response); 
+0

它的工作方式也是如此。谢谢。 – Theo

+0

如果是工作,请接受为答复。 –

+1

这是您的解决方案吗?但是如何? :d – l0rkaY

1

这是什么问题? :)

可能:

if(!email_exists($email,$con)){ 
    $j->status = "fail"; 
    $j->message = "Email does not exist"; 

} 

echo json_encode($j); 
+0

谢谢。它的工作原理:) – Theo

-1

我找到了答案。

if(email_exists($email,$con)){ 
     $error = "Email Exists"; 
     echo json_encode(array('status' => 'success', 'message' => 'Logged in')); 


    }else{ 
     $error = "Email does not exist"; 
     echo json_encode(array('status' => 'fail', 'message' => 'Email not found')); 

    } 

我现在想不出别的什么。

+0

阅读我的答案...:D – l0rkaY