在php上有两个不明索引

时间:2018-02-14 03:50:04

标签: php

我目前在第20行和第24行出错。它说有未定义的索引。当我看到http://yoururl.com/viewwall.php/itemID=123456时,它在第20到24行显示错误,但能够显示userid,timeofposting和message。反正有没有解决这个问题?

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");

include("global.php");

$conn = new mysqli(server, dbuser, dbpw, db);

$itemID = $_GET['itemID'];

$query = "select userid, timeofposting, message from mywall where itemID = '" . $itemID . "' order by timeofposting DESC";

$result = $conn->query($query);

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"wallpostid":"'  . $rs["wallpostid"] . '",'; //error
$outp .= '"userid":"' . $rs["userid"] . '",';
$outp .= '"timeofposting":"' . $rs["timeofposting"] . '",';
$outp .= '"message":"' . $rs["message"] . '",';
$outp .= '"itemID":"'   . $rs["itemID"]        . '"}'; //error
}
$outp .="]";

$conn->close();

echo($outp);
?>

1 个答案:

答案 0 :(得分:0)

首先,您信任来自用户的输入。

应该过滤掉。

$_GET['itemID']取自url并按原样提供给SQL查询。

这很脆弱。

使用mysqli_real_escape_string()

同样,您没有添加检查是否提供。

您正在使用PHP语法返回JSON并动态构建JSON。

只需创建数组并使用json_encode()函数。

所以,最后跟随的是correcetd代码:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");

include("global.php");

$conn = new mysqli(server, dbuser, dbpw, db);

$itemID = isset($_GET['itemID']) ? mysqli_real_escape_string($_GET['itemID']) : NULL;

if (! empty($itemID)) {
    $query = "SELECT userid, timeofposting, message 
        FROM mywall 
        WHERE itemID = '" . $itemID . "' ORDER BY timeofposting DESC";
    $result = $conn->query($query);
    $arr = array();
    while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
        $arr['wallpostid'] = $rs["wallpostid"];
        $arr['userid'] = $rs["userid"];
        $arr['timeofposting'] = $rs["timeofposting"];
        $arr['message'] = $rs["message"];
        $arr['itemID'] = $rs["itemID"];
    }
    echo json_encode($arr);
}
$conn->close();

echo($outp);
?>