php bind_result返回空结果

时间:2015-08-25 21:17:14

标签: php

我已经尝试了我在网上找到的大多数类似的解决方案,但是他们似乎并不是我的 PHP

$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();`

这是我的数据库enter image description here

的图片

2 个答案:

答案 0 :(得分:3)

错误来自$ stmt-> bind_result(); 您的MySQL查询从数据库中选择1列,并绑定5列,这是不可能的。这是应该正常工作的东西:

<div id="scroller-anchor"></div> 
  <div id="scroller" style="margin-top:10px;"> 

或者对于topbanner(),如果要获取数据库中的所有数据,请使用:

$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();

另外,要知道根据你想要如何使用这个函数,当你使用&#34; return&#34;时,你会在第一次出现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()){
        echo $date; //echo whatever column you want
    }
    $stmt->close();
}

因此,使用上面的代码,您可以继续将函数回显为:

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();
}

答案 1 :(得分:0)

确实令人尴尬的答案:您以为您输入了bind_result,但实际上您再次输入了bind_param。结果:无论您做什么,所有“结果”最终都是空的。

我的代码:

$stmt = $mysqli->prepare("select 5 where 5=?") ;
$stmt->bind_param("i", $value);
$stmt->execute();
$stmt->bind_param($five); // oops!  This should have been bind_result
if($stmt->fetch())
{
  // why is $five completely empty?  This is infuriating...
}

事实证明,bind_param在某些情况下可能会无声地失败,并且最终会导致一堆空变量。