1

我一直在尝试在我的 iPhone 应用程序中使用 JSON 来使用 PHP 从我的 SQL 数据库中检索信息。我可以成功发送 JSON 并将其返回给 iPhone 应用程序。当我尝试从发送的 JSON 数组中获取参数时,就会出现我的问题。它失败了,我不确定我的陈述有什么问题。任何建议都会很棒。

function connect($config) {
   try {
     $conn = new \PDO('mysql:host=localhost;dbname=authorization',
                    $config['username'],
                    $config['password']);

     $conn->setAttribute(\PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

     return $conn;              

  }catch(Exception $e){
    return false;
  }
}

function query($conn, $body) {

if (isset($body['authorization'])) {

        // Put parameters into local variables
        $authorization_code = $body['authorize'];
        $device_id = $body['device'];
    }
$stmt = $conn->prepare("SELECT uses_remaining FROM phone_authorization WHERE authorization_code = $authorization_code");
$stmt->execute();
$results = $stmt->fetchAll();
return $results ? $results : false;
}

if ($_SERVER['HTTP_METHOD'] === 'postValues'){ 

    $body;

    if($_POST == null){

        $handle  = fopen('php://input', 'r');
        $rawData = fgets($handle);
        $body = json_decode($rawData);
    }
    else{
        $body == $_POST;
    }

    $conn = connect($config);

    $row = query($conn, $body);

    if ($row) {
        echo json_encode($row);
    }
    else
    {
        $data['value1'] = $row;
        $data['value2'] = "test";
        echo json_encode($data);
    }

}
else {

    $data['error'] = 'The Service you asked for was not recognized';
    echo json_encode($data);
}

谢谢

4

1 回答 1

0

如果您的 $body 是json变量,则必须将其解码为php使用json_decode

function query($conn, $body) {

if (isset($body['authorization'])) {

        // Put parameters into local variables

        $authorization_code =json_decode($body['authorize'], true);
        $device_id = json_decode($body['device'], true);
    }
$stmt = $conn->prepare("SELECT uses_remaining FROM phone_authorization WHERE authorization_code = $authorization_code");
$stmt->execute();
$results = $stmt->fetchAll();
return $results ? $results : false;
}

if ($_SERVER['HTTP_METHOD'] === 'postValues'){ 

    $body;

    if($_POST == null){

        $handle  = fopen('php://input', 'r');
        $rawData = fgets($handle);
        $body = json_decode($rawData);
    }
    else{
        $body == $_POST;
    }

    $conn = connect($config);

    $row = query($conn, $body);

    if ($row) {
        echo json_encode($row);
    }
    else
    {
        $data['value1'] = $row;
        $data['value2'] = "test";
        echo json_encode($data);
    }

}
else {

    $data['error'] = 'The Service you asked for was not recognized';
    echo json_encode($data);
}
于 2013-09-25T19:23:57.157 回答