JSON结果格式

时间:2017-11-09 13:46:50

标签: php json sql-server

<?php
include 'Connection.php';

if(isset($_REQUEST["insert"])) 
{ 
$user = $_GET['user'];
$pwd = $_GET['pass'];

$sql = "select RegNo,UserName,password from Std_Reg where Username= '$user' and Password = '$pwd'";
//$sql = "select * from Std_Reg";
$stmt = sqlsrv_query($conn, $sql);



$result = array(); 

do {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
       $result[] = $row; 
    }
} while (sqlsrv_next_result($stmt));

if(count($result)>0)
{
    $result1['status']=1;//"Login successfully";
    array_push($result,$result1);
}
else
{

    $result1['status']=0;//"Record not found";
    array_push($result,$result1);
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first

echo json_encode($result); //You will get the encoded array variable
}
?>

这给了我:

[{"RegNo":"xyz","UserName":"abc","password":"123"},{"status":1}]. 

我需要:

[{"status":1},{"RegNo":"xyz","UserName":"abc","password":"123"}].

我怎样才能得到上述结果?我应该在PHP文件中更改什么?

1 个答案:

答案 0 :(得分:1)

这里很不对劲。从顶部开始:

  • 您在网址中包含用户的密码,将其保留在浏览器历史记录和许多其他地方
  • 您正在将用户提供的数据插入到数据库查询中而不对其进行清理,您对SQL注入攻击持开放态度
  • 您正在将明文密码存储在数据库中,这使攻击者可以轻松地通过上述注入攻击获取它们
  • 虽然您只有一个
  • ,但您正在遍历多个结果集
  • 如果您要提取单个用户记录,则根本不需要进行while循环
  • 您发送的JSON的MIME类型不正确
  • JSON是一种数据传输格式,它不应该与元素的顺序相关。如果它确实重要,那么有人做错了。

尝试这样的事情:

<?php
include 'Connection.php';

if(isset($_REQUEST["insert"])) {
    // we are using POST and not GET
    $user   = $_POST["user"];
    $pwd    = $_POST["pass"];
//    uncomment this once your passwords are stored securely
//    $pwd    = password_hash($_POST["pass"], PASSWORD_BCRYPT);
    $sql    = "SELECT RegNo, UserName, password FROM Std_Reg WHERE Username = ? AND Password = ?";
    $params = array($user, $pwd);
    // see how the parameters are passed separately and replace the ? in the query
    $stmt   = sqlsrv_query($conn, $sql, $params);
    // we can check for rows before looping through the result set
    if (sqlsrv_has_rows($stmt)) {
        // this is how to append to an array, array_push() is not PHP-like
        $result[] = array("status" => 1);
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
            $result[] = $row; 
        }
    } else {
        // note also the [] construct automatically creates the variable
        $result[] = array("status"=>0);
    }
    sqlsrv_free_stmt($stmt);
    sqlsrv_close($conn);
    // this isn't just plain text
    header("Content-Type: application/json");
    echo json_encode($result);
}
?>