Read data from mysqli_fetch_array like a multidime

2020-04-20 08:23发布

When I use mysqli_fetch_array() I get an array, but how do I read the values? Is a While-Loop the only option, or can I pick any value from a row and column like a multidimensional array with index like row[0] column [3] ?

标签: php mysqli
3条回答
迷人小祖宗
2楼-- · 2020-04-20 08:43

It depends how you are returning your results from the database.

there are flags in your mysqli_fetch_array function which you can set to modify your returned result.

If you use $row = mysqli_fetch_array($result, MYSQLI_ASSOC); or in OOP $row = $result->fetch_array(MYSQLI_ASSOC);

then you can access your returned result as column name in your while loop like $row['name'] or $row['age']

Or if you use $row = mysqli_fetch_array($result, MYSQLI_NUM); or in OOP $row = $result->fetch_array(MYSQLI_NUM);

then you can access your returned result in while loop like $row[0] or $row[3]

Simple example would be

while($row = mysqli_fetch_array($result)) {
    echo $row['name'] . " " . $row['age'];
}

For further information. Read PHP.net Fetch Array

查看更多
男人必须洒脱
3楼-- · 2020-04-20 08:52

while loop fetches you a row per iteration.

You can get all rows as multidimensional array with mysqli_fetch_all

After that you can use pick your values with [rowNum][colNum]

But beware when your result has lot of rows - array can be very big and cause memory or other issues.

Update to clarify:

if you want to receive multidimensional array of rows there are two ways:

First: iterate over mysqli_result with fetch_assoc/fetch_array and append row to array:

$rows = array();
while ($row = mysqli_fetch_array($res)) {
    $rows[] = $row;
}
echo $rows[0]['whatever'];

Second: receive all results with one function call:

$rows = mysqli_fetch_all($res, MYSQLI_ASSOC);
echo $rows[0]['whatever'];

That's all. No more methods are available.

查看更多
Melony?
4楼-- · 2020-04-20 08:53

Your question suggests that your goal is just to get a single value. If that is the case, you should limit your query to only return what you're looking for rather than getting everything and then finding what you want in the results with PHP.

For the column, specify the one column you want instead of using *, (SELECT one_column FROM your_table) and for the row, either use a WHERE clause to select a specific id (provided that is defined on your table) or use a LIMIT clause to select a specific row number from the result set. Then you won't have to fetch in a loop or fetch all. Your query result (if it's successful) will just have one row with one column, and you can fetch once and get your value.

Granted, if you're going to need to do this repeatedly (i.e. in a loop), it isn't the best approach.

查看更多
登录 后发表回答