When and why to use mysqli_fetch_row, mysqli_fetch_object, mysqli_fetch_assoc, mysqli_fetch_array [duplicate]

偶尔善良 提交于 2020-12-25 00:01:07

问题


I understand in some way the differences between mysqli_fetch_row, mysqli_fetch_object, mysqli_fetch_assoc and mysqli_fetch_array.

My question is if they are so similar (if they are really almost the same as many topics say) which should we use? Why should we use the preferred one and is there some performance difference?

I have read some people say never to use mysqli_fetch_array. I am confused. I am reading now some PHP books and all the examples include it. If this is incorrect is it better for me to stop using it while exercising and use something else that you could explain and recommend?

I have also read that these are equal:

mysqli_fetch_array( $result, MYSQLI_ASSOC ) = mysqli_fetch_assoc( $result ) 
mysqli_fetch_array( $result, MYSQLI_NUM ) = mysqli_fetch_row( $result )
mysqli_fetch_array ( $result ) = mysqli_fetch_assoc( $result ) + mysqli_fetch_row( $result )

If they are equal as a concept, are there performance differences? Which should we use? Are the differences because of performance reasons or for the developer's convenience?

I strongly believe that these differences have a big reason and they have different usage and cases, but I cannot find where to use different functions and syntax.


回答1:


These lines from the documentation on php.net are key:

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

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

In cases where two or more columns have the same name the only way to reference the first occurence(s) of that column is by numerical index. In these cases you need mysqli_fetch_row or mysqli_fetch_array with either MYSQLI_BOTH or MYSQLI_NUM as its second argument (in procedural usage).

mysqli_fetch_assoc($result) is just shorthand for mysqli_fetch_array($result, MYSQLI_ASSOC).

mysqli_fetch_object does what you expect: It returns a row of results as an object. Use of this over mysqli_fetch_assoc is a matter of whether an object or an array better represents the record being handled. The object can be of whatever class you want - stdClass is the default.




回答2:


I dont think there is a huge differents, its only that you need only one function to do the same ;)



来源:https://stackoverflow.com/questions/20261041/when-and-why-to-use-mysqli-fetch-row-mysqli-fetch-object-mysqli-fetch-assoc-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!