未定义偏移量:如果数据库中没有记录,则为0

时间:2019-02-22 20:06:15

标签: php

嗨,我想显示来自服务器的图像。当我在DB中获得记录时,它会起作用。但是,如果数据库中没有记录(没有上传img),我想不显示LOGO

这是我的代码:

public function display_logo($service_id){
    $img_path = DB::table("logo_table")->get()->where("service_id",$service_id);        
       return $img_path[0];}


public function my_name($id)
{
    $name = $this->get_user()->where('id',$id);
    $image_path = $this->display_logo($id);
    $count = count($image_path);
    return view('my_object', compact("name","image_path","count"));
}

还有刀片

 @if ($count>0)
    <img src="{{$image_path->logo_path}}{{$image_path->logo_name}}" width=100 height=100";>
@else
    <h2>No image</h2>
@endif

如果DB中有记录,那么我得到了img,但如果没有。我得到:未定义偏移量:0 我该如何解决。 (对不起,如果我的英语不好:))

3 个答案:

答案 0 :(得分:0)

您应该检查$ img_path的有效值或返回null,例如:

  public function display_logo($service_id){
    $img_path = DB::table("logo_table")->get()->where("service_id",$service_id);        
       return (isset($img_path) ? $img_path[0] : NULL );
   } 

答案 1 :(得分:0)

您可以检查返回了多少张图像,如果没有,则返回NO LOGO ...

return (count($img_path)>0) ? $img_path[0] : "NO LOGO";

或者只是检查是否设置了第一张图片...

return isset($img_path[0]) ? $img_path[0] : "NO LOGO";

不确定要返回什么值,只需将"NO LOGO"更改为之后的值。可能需要使用[]

答案 2 :(得分:0)

当试图访问不存在的数组键时,PHP中发生“未定义偏移”异常。在这种情况下,由于没有匹配的记录,因此将返回一个空数组。

此错误可以通过以下代码重现:

$img_path = [];
echo $img_path[0]; // undefined offset exception

可以通过使用null空格运算符(需要PHP 7.0+)或通过在访问索引之前检查索引是否存在来避免未定义的偏移量异常。

使用空合并运算符的解决方案:(PHP 7.0 +)

public function display_logo($service_id){
    $img_path = DB::table("logo_table")->get()->where("service_id",$service_id);  
       // fallback to null if [0] does not exist
       return $img_path[0] ?? null;
}

具有明确检查的解决方案:

public function display_logo($service_id){
    $img_path = DB::table("logo_table")->get()->where("service_id",$service_id);  
       // fallback to null if [0] does not exist
       return isset($img_path[0]) ? $img_path[0] : null;
}