saftutorials.com
MYSQL SELECT DATA

Create the MySQL query for fetching data from a table and then execute it with mysql_query() function. We can fetch data from a table of the database by using MYSQL SELECT statement.

There are many functions in PHP for fetching data but the commonly used function is mysql_fetch_array() function.


This function returns rows as an associative array and numeric array and returns FALSE if there are no rows.


Syntax of MYSQL SELECT statement

SELECT * FROM table_name

or

SELECT column1, column2 FROM table_name


Below is a simple example of fetching data from student table of database

<?php
 $database_host = 'localhost:3036';
 $database_user = 'root';
 $database_pass = '';
 $conn = mysql_connect($database_host, $database_user, $database_pass);
 if(! $conn ) {
   die('Could not connect: ' . mysql_error());
 }else{
   echo 'Connected successfully\n';
}
 $selected_or_not = mysql_select_db( 'xyz_school' );
 if(! $selected_or_not ) {
   die('Not Selected xyz_school database');
 }else{
   echo 'Selected xyz_school database';
}
 $sql = 'SELECT * FROM student';
 $result = mysql_query( $sql, $conn );
 if(! $result ) {
  die('Could not get data: ' . mysql_error());
 }
 mysql_close($conn);
?>
<!DOCTYPE html>
<html>
<body>
    <h2>Student List</h2>
     <table>
        <th>
           <td>S No</td>
           <td>Student Name</td>
           <td>Address</td>
           <td>Enrollment No</td>
           <td>Joining date</td>
        </th>
<?php
$i = 1;
while($row = mysql_fetch_array($result)) {
?>
        <tr>
           <td><?php echo $i++;?> </td>
           <td><?php echo $row['student_name'] ."or". $row[1]; ?> </td> // Note: You can use declare data by using Column name or Column number, First column number start from 0.
           <td><?php echo $row['student_address'] ."or". $row[2]; ?> </td>
           <td><?php echo $row['student_enrollment_no'] ."or". $row[3]; ?> </td>
           <td><?php echo $row['join_date'] ."or". $row[4]; ?> </td>
        </tr>
<?php
}
?>
     </table>
  </body>
</html>
This code produces the following result:
Output:
S NoStudent NameAddressEnrollment NoJoining Date
1JohnCalifornia1010/02/2017
2JakobNew York2020/05/2017


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic