使用PHP、MySQLi和准备好的语句以数组的形式返回结果


Returning result in array of arrays with PHP, MySQLi and prepared statements

我正在处理以下代码:

$UID = $_POST['userID'];
$rows = [];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
$sql = "SELECT tname, tlname, tadd, tphone FROM `users` WHERE userID =?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $UID);
$stmt->execute();
$stmt->bind_result($tname, $tlname, $tadd, $tphone);
$rows = $stmt->fetchAll();
$stmt->close();
$conn->close();
echo json_encode($rows);

我需要的是得到像一样的结果

 [
    ["foo", "foo", "foo", "foo"],
    ["foo", "foo", "foo", "foo"],
    ["foo", "foo", "foo", "foo"],
    ["foo", "foo", "foo", "foo"]
 ]

更新

我试着通过做到这一点

 while($stmt->fetch()){
            array_push($rows, $tname, $tlname, $tadd, $tphone);
        }

但这是将所有值添加到一个大数组中!

mysqli_stmt::execute()用于insertupdatedelete语句。它不返回结果集,而是返回受语句影响的行数。当执行select时,您需要使用mysqli_stmt::get_result(),它将返回一个mysqli_result实例。然后,您可以在mysqli_result上调用fetch_all(),以检索结果集的所有行作为关联数组的数组。