简体   繁体   English

与mysqli_fetch_array混淆

[英]Confusion with mysqli_fetch_array

I am unfamiliar with the mysqli_fetch_array and can't seem to figure this out. 我对mysqli_fetch_array不熟悉,似乎无法弄清楚。 I have the following code: 我有以下代码:

function select_fetch_row ($arg1, $arg2) {
    $con = new mysqli(/* ... */);
    $query = "SELECT $arg1 FROM $arg2";
    $select = mysqli_query($con, $query);
    while($row = mysqli_fetch_array($select, MYSQLI_NUM)){
        echo $row[0];
    }

}

select_fetch_row(/* parameters*/);

However I'm not understanding what it's supposed to be doing. 但是我不明白它应该在做什么。 I was expecting to obtain an array where each key would correspond to a row in my table, but when I output my code, rather than just having the value of the first row ( $row[0] ) echoed, all the values of the column get echoed. 我期望获得一个数组,其中每个键都对应于表中的一行,但是当我输出代码时,不仅仅是回显第一行( $row[0] )的值,而是专栏得到回应。 Can someone shed some light on how this function really works? 有人可以阐明此功能的实际工作原理吗?

while($row = mysqli_fetch_array($select, MYSQLI_NUM)){
        echo $row[0];
    }

You're fetching the rows one by one, not in a single array. 您要一一读取行, 而不是单个数组。 So each $row variable has a single row from your table, with each key containing a column value. 因此,每个$ row变量在表中都有一行,每个键包含一个列值。 So when you echo $row[0], you're showing the first column of the row you've returned. 因此,当您回显$ row [0]时,您将显示返回的行的第一列。

If you change the parameter MYSQLI_NUM to MYSQLI_ASSOC, you'll have a better idea of what's happening (the array keys will contain the column names instead of integers). 如果将参数MYSQLI_NUM更改为MYSQLI_ASSOC,您将更好地了解发生了什么(数组键将包含列名而不是整数)。

If you want to fetch all the rows in one go, you can use mysqli_fetch_all instead, which will give you one big array, containing one row per key. 如果要一次性获取所有行,则可以改用mysqli_fetch_all,这将为您提供一个大数组,每个键包含一行。

http://www.php.net/manual/en/mysqli-result.fetch-array.php http://www.php.net/manual/zh/mysqli-result.fetch-array.php

http://www.php.net/manual/en/mysqli-result.fetch-all.php http://www.php.net/manual/zh/mysqli-result.fetch-all.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM