使用PHP

时间:2015-09-14 09:57:09

标签: 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";


    }

}

&GT;

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

&GT;

我正在做的是从数据库中选择ID并检查电子邮件是否存在

mysqli_num_rows(query)

功能。如果它返回1或true,则存在电子邮件,以便用户可以登录。如果不是意味着我们返回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";

感谢。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:-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'));

    }

我现在想不出任何其他事情。