doupu1957 2016-09-23 18:45
浏览 314

从SQL数据库返回数据的JSON始终返回NULL

I can't figure out why my php script always returns NULL. I'm developing an Android app that gets user data from a database via a PHP script that returns JSON data. The app parses the data, but I can't get the PHP script to return anything other than NULL. The app uses JSON data for both the data returned for the user, and the result, which is either 1 or 0. I'm still new to PHP, so I'm a bit confused.

Here's my PHP script:

<?php
define('HOST','localhost');
define('USER','user');
define('PASS','password');
define('DB','database');

if (!empty($_POST)){

    if (empty($_POST['userID'])){
        $response["success"] = 0; 
        $response["message"] = "Please enter a User ID";
        die(json_encode($response));
    }

$userID = mysql_escape_string($_POST['userID']); 

$con = mysqli_connect(HOST,USER,PASS,DB);



$result = mysql_query("SELECT* FROM users WHERE id = $userID");


if ($result && mysql_num_rows($result) > 0){

    $response["result"] = array(); 

    while($row = mysql_fetch_array($result)){
        $finduser = array(); 
        $finduser["id"] = $row["id"]; 
        $finduser["firstname"] = $row["firstname"]; 
        $finduser["company"] = $row["company"]; 
        $finduser["position"] = $row["position"]; 

        array_push($response["result"], $finduser);     
    }

    $response["success"] = 1; 
}

echo json_encode($response); 




} else {
?>
        <h1>Search by User ID:</h1> 
        <form action="searchbyuserid.php" method="post"> 
            Enter the UserID of the receipient:<br /> 
            <input type="text" name="userID" placeholder="User ID" /> 
            <br /><br /> 
            <input type="submit" value="Submit" /> 
        </form> 
        <a href="register.php">Register</a>
    <?php
}

?> 
  • 写回答

1条回答 默认 最新

  • dongyi5425 2016-09-23 18:55
    关注

    You're using improper if-else format and also should have a Fatal Error with your code:

    }
    
    echo json_encode($response); // don't put anything between the close of the if and the beginning of the next block
    
    //the next closing brace (or the previous one) shouldn't be here
    } else {
    

    Even if the brace above is just an artifact here and not in your actual code, you can't have anything between the end of the if block {} and the start of the next else/elseif block {}. Check your PHP error log - you should have a fatal error.

    Also, as other users have stated, you are mixing mysql() and mysqli() functions, which is a no-no.

    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗