从MSQL数据库返回数据的JSON总是返回NULL


JSON returning data from MSQL database always returns NULL

我不明白为什么我的php脚本总是返回NULL。我正在开发一个Android应用程序,它通过返回JSON数据的PHP脚本从数据库中获取用户数据。该应用程序解析数据,但我无法让PHP脚本返回NULL以外的任何内容。该应用程序将JSON数据用于为用户返回的数据和result,后者为1或0。我还是PHP的新手,所以我有点困惑。

这是我的PHP脚本:

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

您使用了不正确的if-else格式,并且您的代码中应该有一个Fatal Error

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

即使上面的大括号在这里只是一个工件,而不是在实际代码中,在if块{}的末尾和下一个else/elseif块{}的开头之间也不能有任何东西。检查你的PHP错误日志-你应该有一个致命的错误。

此外,正如其他用户所说,您将混合使用mysql()mysqli()函数,这是一个禁忌。