json_encode和json_decode在mySql中的误解

时间:2017-06-06 13:02:12

标签: php mysql json

在完成9999次测试后的几天内,我被困在json_encode的PHP页面中。

目标是使用mySql数据库登录swift应用程序。

所以我猜我的查询有问题,我不知道如何在json_encode()中发送找不到用户的答案。

这是我的php代码:

<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);

// i get the email and password sent as parameter
// my swift code is working, and the next line is ok.
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);

//echo json_encode($logs); // to send back my logs (ok)

// Create connection
$con = mysqli_connect("localhost", "xx", "xx", "xx");

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//echo json_encode($logs);
// its working until here if i execute the previous line and put the rest in comment 

// from the next line its making errors such : 
// Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." 
$sql = "SELECT * FROM clients WHERE email = '".$logs['email']."'";

//echo json_encode($logs); //not working at this place if i put the rest in comment.

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    //check the corresponding password
    if ( $logs['pass'] == $resultArray[4]) {
        // i m not sure how to send the answer as a json
        echo json_encode(true);

    } else {
        echo json_encode(false);
    }

}

// Close connections
mysqli_close($con);

?>    

如果我在没有所有json东西的情况下尝试使用php,那么自从我放入它以后它的工作 $sql = "SELECT * FROM clients WHERE email = 'ben@test.be'"; 作为测试。

以下代码有效:

<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);

$con = mysqli_connect("localhost", "xx", "xx", "xx");

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "SELECT * FROM clients";

if ($result = mysqli_query($con, $sql))
{
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}
echo json_encode($emparray);
}

mysqli_close($con);

?>

但如果我放$sql = "SELECT * FROM clients WHERE email = '$logs['email']'";而不是$sql = "SELECT * FROM clients"; 它不再工作了。它不喜欢我的条件查询。我误解了什么?

0 个答案:

没有答案