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]
?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
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
For further information. Read PHP.net Fetch Array
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:Second: receive all results with one function call:
That's all. No more methods are available.
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 aWHERE
clause to select a specific id (provided that is defined on your table) or use aLIMIT
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.