PHP mySQLi DB Connect and Show Results in Loop Example

by Hiroshi on January 31, 2013

in Select

Here is how to use mySQLi, connect to the db and display records in loop.

Database Connection

<?php
// Connect To DB
$hostname="localhost";
$database="mydbname";
$username="root";
$password="";
 
@$conn = mysqli_connect($hostname, $username, $password)
        or die("Could not connect to server " . mysql_error()); 
    mysqli_select_db($conn, $database)
        or die("Error: Could not connect to the database: " . mysql_error());
 
    /*Check for Connection*/
    if(mysqli_connect_errno()){
        // Display Error message if fails
        echo 'Error, could not connect to the database please try again again.';
    exit();
    }
?>

Displaying Records in Loop

<?php
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = mysqli_query($conn, $query);
@$num_results = mysqli_num_rows($result);
?>
<?php
/*Loop through each row and display records */
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
?>
 
<?php // echo 'Name' .$row['ssfullname'] . 'email' . $row['ssemail'] . "\n"; ?>
 
Name: <?php print $row['ssfullname']; ?>
<br />
Email: <?php print $row['ssemail']; ?>
<br /><br />
 
<?php 
// end loop
} 
?>

Display single Record using mySQLi

Related Posts

Previous post:

Next post: