2015-08-25 240 views
1

我曾嘗試大多同類解決方案我在網上找到,但他們不似乎worrk這是我 PHPPHP bind_result返回空結果

$db_host = "localhost"; 
$db_name = "nm"; 
$db_user = "root"; 
$db_pass = ""; 
$mysqli_news = new mysqli($db_host, $db_user, $db_pass, $db_name); 

function topbanner() 
{ 
    global $mysqli_news; 
    $stmt = $mysqli_news->prepare("SELECT date FROM Ftemp_news_top_pic ORDER BY id DESC LIMIT 3"); 
    $stmt->execute(); 
    $stmt->bind_result($id, $image, $link, $source, $date); 
    while ($stmt->fetch()){ 
     return $date; 
    } 
    $stmt->close(); 


} 

echo topbanner();` 

和本我的分貝的PIC enter image description here

+0

我應該:'$ mysqli_news'可以和它在哪兒定義? – Rizier123

+0

@ Rizier123我eddited它 –

回答

2

錯誤來自$ stmt-> bind_result(); 您的MySQL查詢從數據庫中選擇1列,並綁定5列,這是不可能的。這裏是應該正常工作:

$db_host = "localhost"; 
$db_name = "nm"; 
$db_user = "root"; 
$db_pass = ""; 
$mysqli_news = new mysqli($db_host, $db_user, $db_pass, $db_name); 

function topbanner() 
{ 
    global $mysqli_news; 
    $stmt = $mysqli_news->prepare("SELECT date FROM `Ftemp_news_top_pic` ORDER BY `id` DESC LIMIT 3"); 
    $stmt->execute(); 
    $stmt->bind_result($date); 
    while ($stmt->fetch()){ 
     echo $date; // echo/return $date column 
    } 
    $stmt->close(); 
} 

echo topbanner(); 

或爲topbanner()如果你想獲得在數據庫中,使用的所有數據:

function topbanner() 
{ 
    global $mysqli_news; 
    $stmt = $mysqli_news->prepare("SELECT * FROM `Ftemp_news_top_pic` ORDER BY `id` DESC LIMIT 3"); 
    $stmt->execute(); 
    $stmt->bind_result($id, $title, $image, $link, $source, $date); 
    while ($stmt->fetch()){ 
     echo $date; //echo whatever column you want 
    } 
    $stmt->close(); 
} 

而且,知道,這取決於你如何想要使用函數,當你使用「return」的時候,你在while循環的第一次出現之後結束函數,如果你想獲得所有可用的值,你可以將結果附加到while循環的變量中,在函數結尾處返回變量,如下所示:

function topbanner() 
{ 
    global $mysqli_news; 
    $stmt = $mysqli_news->prepare("SELECT * FROM `Ftemp_news_top_pic` ORDER BY `id` DESC LIMIT 3"); 
    $stmt->execute(); 
    $stmt->bind_result($id, $title, $image, $link, $source, $date); 
    while ($stmt->fetch()){ 
     $result .= $date; //Append results to a variable 
    } 
    return $result; 
    $stmt->close(); 
} 

因此,與上面的代碼,你可以繼續呼應功能:

echo $topbanner();