2016-08-06 52 views
0
function get_description($table, $id){ 
    global $conn; 

    if ($id!='') { 
     $sql = "SELECT * FROM ".$table." WHERE id=".$id; 
    $result = mysqli_query($conn, $sql); 

    if (!$result) { 
     die("Connection failed: " . mysqli_error($conn)); 
    } 

    if (mysqli_num_rows($result) < 1) { 

    }else{ 
     $rows = mysqli_fetch_assoc($result); 
     $description = $rows['description']; 

    } 

    return $description; 
}else{ 
    return ""; 
} 
} 

我在我的functions.php中有這個函數。我試圖下載一個CSV文件,它下載CSV文件,但給出了CSV文件的返回函數 - 未定義通知錯誤 - 下載csv文件

公告標題中的通知:

未定義的變量:描述 /VAR /www/html/include/functions.php on line 73

73行是指 - return $ description;

我想擺脫csv文件的通知錯誤。

回答

1

在某些情況下,您只能指定$description,而您始終將其返回。你應該在你的函數的開頭用NULLFALSE這樣的默認值分配它,或者在這種情況下可能是一個空字符串。

function get_description($table, $id){ 
    global $conn; 
    $description = ""; 
    ... 
1

你只有時定義變量:

if (mysqli_num_rows($result) < 1) { 

}else{ 
    $rows = mysqli_fetch_assoc($result); 
    $description = $rows['description']; 
} 

因此,如果在執行if塊(不是else塊),該變量被從未定義。定義它的第一個條件之外,所以它始終至少有一定的價值:

$description = ""; 
if (mysqli_num_rows($result) < 1) { 

}else{ 
    $rows = mysqli_fetch_assoc($result); 
    $description = $rows['description']; 

} 
+0

謝謝,功效神奇:) – CNk

0

只要檢查你的代碼,錯誤信息是非常簡單的在這種情況下 - 「未定義的變量:說明」。這意味着你正在返回未定義的變量。如果(mysqli_num_rows($ result)< 1)語句部分針對肯定條件執行,則不會定義$ description變量。將代碼更改爲:

function get_description($table, $id){ 
    global $conn; 
    $description = ""; 

    if ($id!='') { 
     $sql = "SELECT * FROM ".$table." WHERE id=".$id; 
     $result = mysqli_query($conn, $sql); 

     if (!$result) { 
      die("Connection failed: " . mysqli_error($conn)); 
     } 

     if (mysqli_num_rows($result) >= 1) { 
      $rows = mysqli_fetch_assoc($result); 
      $description = $rows['description']; 
     } 
    } 
    return $description; 
} 
0

問題是返回$ description,因爲它沒有在所有情況下定義。

使用下面的代碼

if(isset($description)) 
{ 
    return $description; 
}