PHP脚本中的错误,未定义的变量

时间:2017-11-12 04:44:29

标签: php

<?PHP
include_once("connection.php");

$username = $_POST['txtUsername'];

$query = "SELECT * FROM cart_management WHERE UserName = '$username' ORDER BY Cart_Name ASC"; 

$result = mysqli_query($conn, $query);

while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
}
echo json_encode($data)
?>

enter image description here

请帮我解决这个问题,我无法解决这个问题?

2 个答案:

答案 0 :(得分:0)

您需要检查您发送的数据是否具有必须相同的索引txtUsername。 (查看你在哪里打电话cartRetrive.php api)

,第二个错误是未定义的变量。

您在宣布之前尝试使用$data[]

<?PHP
include_once("connection.php");

$username = $_POST['txtUsername']; // check the index from where you are calling  cartRetrive.php

$query = "SELECT * FROM cart_management WHERE UserName = '$username' ORDER BY Cart_Name ASC"; 

$result = mysqli_query($conn, $query);

car data[] = array();// declare variable here

while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
}
echo json_encode($data)
?>

答案 1 :(得分:0)

您应首先检查txtUsername,这是您在屏幕截图中的首次通知。其次,在$data循环中使用它之前,您应该将while声明为空数组,否则会导致屏幕截图中的第二个通知:

if($_POST['txtUsername'] && $_POST['txtUsername'] != '') {
    $username = $_POST['txtUsername'];
    $data = [];
    $query = "SELECT * FROM cart_management WHERE UserName = '$username' ORDER BY Cart_Name ASC"; 

    $result = mysqli_query($conn, $query);

    while($row = mysqli_fetch_assoc($result)){
        $data[] = $row;
    }
    echo json_encode($data);
}