这是我的模特功能:
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()
,但每次都得到这个:
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-&gt; 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;
}
}
提前致谢。
答案 0 :(得分:0)
bind_result 设置函数本地范围内的变量。您没有正确返回变量。您只返回 $ stmt 。您需要在函数中获取结果,然后返回结果。一个例子:
$results = [];
while ($stmt->fetch()){
$results[] = [
'name': $name,
];
}
return $results;
因此,您当前正在尝试访问定义变量的函数之外的变量。 ( bind_results 是设置变量)。
以下是有关范围的PHP文档的链接:http://php.net/manual/en/language.variables.scope.php。