PHP mySQLi DB Connect and Show Single Result Example

by Hiroshi on January 31, 2013

in Select

Here is how to use mySQLi, connect to the db and display a single record from database.

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 Single Record

<?php
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = mysqli_query($conn, $query);
@$num_results = mysqli_num_rows($result);
 
$row = mysqli_fetch_row($result);
// or
// $row = mysqli_fetch_assoc($result);
?>
<?php
$ssfullname = $row['ssfullname'];
$ssemail    = $row['ssemail'];
print $ssfullname;
print $ssemail;
?>
 
OR
 
<?php
print $row['ssfullname'];
print $row['ssemail'];
?>

Display records in loop using mySQLi

Related Posts

Previous post:

Next post: