mysql_fetch_assoc() Function in PHP
What is mysql_fetch_assoc() function in PHP?
How does mysql_fetch_assoc() works?
Explanation
mysql_fetch_assoc function fetches query result row as an associative array.
Syntaxarray mysql_fetch_assoc ( resource result [, int result_type])
Returns an Associative array containing one row of query data; FALSE when out of data or on error.
mysql_fetch_assoc() function allows you to access data stored in the result returned from a successful execution of mysql_query function . This takes one row from a MySQL result, and converts it to an associative array with each field name as a key and the matching field value as the value. Mysql_fetch_assoc() increments its position each time it is called ie.,when it is called first time, it reads the first row, the second time the second row, etc, until end of the result returned by
mysql_query().
Example:
<?php //Attempt to connect to the default database server $link = mysql_connect("mysql_host", "mysql_user", "mysql_password") or die ("Could not connect"); //select database if (!mysql_select_db("my_database", $link)) { echo " ERROR NO: " . mysql_errno($link) . "n"; } $query="select user_id,user_name,user_status from user_table"; //execute query $result=mysql_query($query,$link); //fetch query result row as an associative array while ($row = mysql_fetch_assoc($result)) { echo $row["user_id"]; echo $row["user_name"]; echo $row["user_status"]; } mysql_close($link); ?> |
In the above example, connection to the default database server is established. The database 'my_database' is selected. After the successfull execution of the query, result is passed to mysql_fetch_assoc function, here first row is fetched for the query result and values are displayed. Mysql_fetch_assoc function is executed repeatedly in loop to fetch all the rows of the query result till the end of the result
RESULT:
1
JOHN
ACTIVE2
MARIA
INACTIVE3
EDWARD
ACTIVESee also: mysql_fetch_row(),
mysql_fetch_array(),
mysql_query() and
mysql_error().