mysqli_fetch_array和MYSQLI_BOTH有什么区别?

2022-08-30 23:55:20

我知道那件事

mysqli_fetch_assoc,
mysqli_fetch_array,
mysqli_fetch

但是,它们是否等于或实际上不同?MYSQLI_BOTHmysqli_fetch_array


答案 1

来自 PHP 手册:

通过使用MYSQLI_ASSOC常量,此函数的行为将与mysqli_fetch_assoc()相同,而MYSQLI_NUM的行为将与mysqli_fetch_row()函数相同。最后一个选项MYSQLI_BOTH将创建一个具有两者属性的数组。

这些是用于指示将返回的类型的可选参数array

以下是基本示例:

$result->fetch_array(MYSQLI_NUM);

array(
    0 => "val 1",
    1 => "val 2"
);

$result->fetch_array(MYSQLI_ASSOC);

array(
    'key0' => "val 1",
    'key1' => "val 2"
);

$result->fetch_array(MYSQLI_BOTH);

array(
    0 => "val 1",
    'key0' => "val 1",
    1 => "val 2",
    'key1' => "val 2"
);

PHP 手册


答案 2

mysqli_fetch_array()

function 还可以将数据存储在关联索引中,使用结果集的字段名称作为键。

例如

<?php
    mysqli_connect("localhost", "mysql_user", "mysql_password") or
        die("Could not connect: " . mysqli_error());
    mysqli_select_db("mydb");

    $result = mysqli_query("SELECT id, name FROM mytable");

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        printf ("ID: %s  Name: %s", $row["id"], $row["name"]);
    }

    mysqli_free_result($result);
?>

MYSQLI_BOTH

将创建具有两者属性的单个数组。

例如

<?php
    mysqli_connect("localhost", "mysql_user", "mysql_password") or
        die("Could not connect: " . mysqli_error());
    mysqli_select_db("mydb");

    $result = mysqli_query("SELECT id, name FROM mytable");

    while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
        printf ("ID: %s  Name: %s", $row[0], $row["name"]);
    }

    mysqli_free_result($result);
?>

推荐