【问题标题】:Issue with using mysqli statement as a function return使用 mysqli 语句作为函数返回的问题
【发布时间】:2017-12-17 04:04:34
【问题描述】:

这是我的模型函数:

  public function getAllArticles(){
    $stmt = $this->mysqli->prepare("select * from articles where 1 = 1");
    $stmt->execute();
    $stmt->bind_result($id, $name, $title, $excerpt, $content, $created_at, $updated_at);
    return $stmt;
}

我正在尝试将 mysqli 语句作为我的函数返回返回,以将其作为函数调用值分配给此函数内的变量:

 public function index(){
    $model = new IndexModel();
    $out = $model->getAllArticles();
    Template::render('index', THEME_FOLDER, ['results' => $out]);
}

这是试图返回正确主题的渲染函数:

 public static function render($theme, $base_folder = THEME_FOLDER, $var = null){
    $theme = str_replace('.php', '', $theme);
    if(!self::theme_exists($theme, $base_folder))
        die("Template {$theme}.php could not be found in the {$base_folder} Directory.");
    require_once ($base_folder . $theme . '.php');
}

这是 index.php,我尝试循环遍历 $var['results']->fetch() 但 O 每次都得到这个:

Notice: Undefined variable: name in C:\xampp\htdocs\wiche\theme\index.php on line 15

这是 index.php:

    <?php
    $statement = $var['results'];
    while ($statement->fetch()){
        echo $name;
    }
?>

PS:当我在 IndexModel.php (getAllArticles()) 中使用 $stmt->fetch() 时,我可以获得正确的结果。但是当我将 $stmt 作为函数调用值返回时,我无法将返回的 mysqli 语句与 fetch() 函数一起使用:

    public function getAllArticles(){
    $stmt = $this->mysqli->prepare("select * from articles where 1 = 1");
    $stmt->execute();
    $stmt->bind_result($id, $name, $title, $excerpt, $content, $created_at, $updated_at);
    //return $stmt;
    while ($stmt->fetch()){
        echo $name;
    }
}

提前致谢。

【问题讨论】:

  • 正如错误所说,您的变量 $name 未定义...您从哪里获取变量以传递给 bind_result()
  • 帖子已编辑。请检查一下。
  • 再一次,你的变量 $name 是在哪里设置的?我没有看到你在任何地方设置它,所以你的错误说它未定义也就不足为奇了?

标签: php function mysqli return


【解决方案1】:

bind_result 将变量设置在函数的本地范围内。您没有正确返回变量。您只是返回 $stmt。您需要在函数中获取结果,然后返回结果。一个例子:

$results = [];
while ($stmt->fetch()){
    $results[] = [
       'name': $name,
    ];
}
return $results;

因此,您当前正试图访问定义该变量的函数之外的变量。 (bind_results 正在设置变量)。

这里是关于范围的 PHP 文档的链接:http://php.net/manual/en/language.variables.scope.php

【讨论】:

  • 很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 2012-01-31
相关资源
最近更新 更多