Punjabi revolution tutorials PHP MySQL Connection Part 2 selection

PHP MySQL – Retrieving table records using Select query

In retrieving records from database, when we run the select query, it returns the result in the form of a result set. You can conceive the result set as a table or a two dimensional array. From this result set, we get a row at a time. The row is retrieved as an associative array. You know in associative array, we get the values using keys instead of indexes. Here the keys values are the actually column names of the mysql table used in sql query.

Here is a sample code followed by explanation.

Line 8 to 14 : Here an html table with heading row is rendered. The actual contents of table follow based on the table records.

Line 18 : The string of select sql query.

Line 19: For select queries, the statement $rs = $con->query($q); returns result set instead of boolen. The result set can be understood like a 2 d array.

Line 20: the statement $r = $rs->fetch_assoc() puts a 1 d associative array in the variable $r. the array is actually a single row of the result set. Every time, the statement is executed, it fetches the next row. Finally when it reaches the end of the result set, the expression returns false result, resulting in the end of while loop.

Line 21 to 26 : renders a table row with contents from the data set row. It renders a single row in each iteration.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *