我在Delivary()类下创建了一个公共函数View()。但在第40行,我返回$ arr。现在它显示Undefined变量:arr当我的数据表为空时。 注意:未定义的变量:第40行的C:\ xampp \ htdocs \ online shop \ dataAccessLayer \ dalDelivary.php中的arr
我的代码是:
class Delivary {
public $place;
public $address;
public $amount;
public $date;
public $payment;
public $walletnumber;
public $user_id;
public function DB()
{
$connection = mysqli_connect("localhost","root","","project");
return $connection;
}
public function Insert()
{
$sql = "INSERT INTO delivery (place, address, amount, `date`,payment, walletnumber, user_id) VALUES
('$this->place', '$this->address', '$this->amount', '$this->date', '$this->payment', '$this->walletnumber', '$this->user_id');";
if(mysqli_query($this->DB(), $sql))
{
return true;
}
return false;
}
public function View()
{
$sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
$result = mysqli_query($this->DB(),$sql);
while($d = mysqli_fetch_row($result))
{
$arr[] = $d;
}
return $arr; //line 40
}
public function Delete()
{
$sql = "DELETE FROM delivery WHERE delivery_id = '".$this->delivery_id."'";
if(mysqli_query($this->DB(), $sql))
{
return true;
}
return false;
}}
答案 0 :(得分:0)
在将数组定义为数组之前,您将像数组一样访问$arr
。要消除此通知(这不是警告而不是错误),只需在使用之前定义数组:
$arr = [];
while($d = mysqli_fetch_row($result))
{
$arr[] = $d;
}
return $arr; //line 40
确保您正在检查mysqli_query
函数返回时的错误:
$conn = $this->DB();
$sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
$result = mysqli_query($conn, $sql);
if ( !$result ) {
echo "There was an error executing this query: ", mysqli_error($conn);
exit;
}
$arr = [];
while($d = mysqli_fetch_row($result))
{
$arr[] = $d;
}
return $arr;
答案 1 :(得分:0)
更改
public function View()
{
$sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
$result = mysqli_query($this->DB(),$sql);
while($d = mysqli_fetch_row($result))
{
$arr[] = $d;
}
return $arr; //line 40
}
要
public function View()
{
$arr = [];
//Please correct the following SQL statement as per your requirement.
$sql = "SELECT delivery.delivery_id, service.area, delivery.address, delivery.amount, delivery.date, delivery.payment, delivery.walletnumber, delivery.user_id FROM delivery, service WHERE service.service_id = delivery.place";
$result = mysqli_query($this->DB(),$sql);
while($d = mysqli_fetch_row($result))
{
$arr[] = $d;
}
return $arr; //line 40
}
错误应该去了。由于您在while循环中直接推送到$ arr,因此如果查询返回0条记录,PHP无法找到$ arr。由于您的查询返回0条记录,因此它不会执行while loop
中的代码,因此PHP不知道$ arr。