Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to fetch data from database in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 106
    Comment on it

    For fetching data from database  in php, first we have to create a connection from database by using following code.

     

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "pass";
    $database = "demo"; //this will contain name of a database
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
        
    ?>
    

    Below code will fetch data from database in the form of a table.

    $sql = "SELECT * FROM user"; 
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {?>
       
        <table>
    		 <tr>
    			 <th>ID</th>
    			 <th>NAME</th>
    			 <th>PHONE NUMBER</th>
     			 <th>EMAIL</th>
     			 <th>GENDER</th>
     			 <th>Action</th>
    		</tr>
    	<?php
      while($row = $result->fetch_assoc()) {?>  // storing result in associated array form
        	<tr>
    	    	<td><?php echo $row["id"];?></td>
    			<td><?php echo $row["Name"];?></td> 
    			<td><?php echo $row["phone"];?></td>
    			<td><?php echo $row["email"];?></td>
    			<td><?php echo $row["gender"];?></td>
    			<td>
    			
    			</td>
    		</tr>
    <?php 
            
        }
        echo '</table>';
        
        } 
    else 
    
        {
          
          echo "0 results";
        }
    
    
    
    
    
    
    
       		
    $conn->close();
    
    
    
    ?>
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: