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


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

下面的第一个脚本运行良好,并返回带有数据的多行。但是当我试图在函数中使用此代码时,如第二个脚本所示,我不能输出数据,但它返回行数,我试图使用返回数组(),如这里所示,但我仍然无法弄清楚它的工作。多谢。

<?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 = test ($mysqli, $id);

然后bind_result返回语句 ->

美元支撑bind_result(名称、城市美元);

为了方便,请使用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>' ; 
}