mysqli bind_result 然后使用 fetch() 获取结果 - 不在函数内部工作

mysqli bind_result and then get results using fetch() - not working inside a function

以下第一个脚本运行良好,return 多行数据。但是当我尝试在第二个脚本中所示的函数中使用此代码时,我无法输出数据,但它 return 行数,我尝试使用 return array() ,如图所示here 但我仍然无法弄清楚它是否有效。非常感谢。

<?php
// 1st code
$stmt = $mysqli -> prepare (" SELECT Name, City FROM user_db WHERE id = ? " ) ;
$stmt -> bind_param ('s', $id ) ;
$stmt -> execute () ;
$stmt -> store_result () ;
$stmt -> bind_result ( $name1, $city1  ) ;
while ( $stmt -> fetch () ) { echo $name1 .'-'. $city1  .'<br>' ; }

第一个代码的结果

name1-city1
name2-city2
name3-city3

第二个代码 - 在函数中使用第一个代码

function test ( $mysqli , $id ) {
    $stmt = $mysqli -> prepare (" SELECT Name, City FROM user_db WHERE id = ? " ) ;
    $stmt -> bind_param ('s', $id ) ;
    $stmt -> execute () ;
    $stmt -> store_result () ;
    $stmt -> bind_result ( $name, $city  ) ;
    return $stmt;
}

$stmt = test ( $mysqli , $id );

while ( $data = $stmt -> fetch () ) { 
    echo  $name .'-'. $city  .'<br>' ; 
}

第二个代码的结果

-
-
-

bind_result 调用该函数后得到与第一个脚本相同的结果,它是我正在寻找的解决方案,但我仍然不明白为什么上面的第二个脚本没有按预期工作

调用函数

$stmt = 测试 ($mysqli, $id);

然后bind_result到语句

$stmt -> bind_result ($name, $city);

看在上帝的份上,使用 PDO

function test ( $db , $id ) {
    $stmt = $db->prepare ("SELECT Name, City FROM user_db WHERE id = ?") ;
    $stmt->execute([$id]);
    return $stmt->fetchAll();
}

$data = test ($pdo, $id);

foreach ($data as $row) { 
    echo  $row['Name'] .'-'. $row['City']  .'<br>' ; 
}