Selecting and Displaying records from database using php and mysql

Selecting and Displaying records from mysql table using php is quite easy.

These are the steps that should be followed.
  1. Include connection file.
  2. Write and execute query.
  3. Apply while loop to get all results

Please see the images in order to completely understand how to select and display the records using php and mysql



Code




mysql_fetch_array() is used to fetch regular array, row by row from the result set and this process goes on until it reaches the last row if this function is inside while loop, if this function is not inside while loop then it fetchs only one row from the result set and focus move to the next code segment of the php program.

In our php program we need to display all the records that match our query so we use mysql_fetch_array() inside the while loop and also display every row one by one using echo statement.

Let's understand php code use for selecting and displaying records from mysql database

require_once('conn.php');
we first include the connection file in our php program. In this connection file we define host which is localhost, user which is by default root, database name and then mysql_connect() function to establish connection with database and then mysql_select_db() function to select the database. To know exactly how to create connection with database using php please read this post.

$select_query="select * from student";
We write a query to select all the records from the student table and then assign this query to a variable $select_query

$result=mysql_query($select_query);

mysql_query($select_query) is used to execute the query, it takes query as a parameter, in the above line the query is executed and result set is store inside the variable $result. and then we apply mysql_fetch_array() to display rows from resultset one by one. mysql_fetch_array() takes result set as a parameter.




Output


0 comments: