Simple Database Connection using MySQLi OOP and Procedural

Date Posted: February 23, 2015, 3:53 am


OOP Approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
$server_name    = 'localhost';
$username       = 'root';
$password       = '';
$db_name        = 'carlofontanos';

$conn = new mysqli($server_name, $username, $password, $db_name);

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

$sql = 'SELECT * FROM wp_posts WHERE post_type = "post"';
$result = $conn->query($sql);

if ($result->num_rows > 0) {
   
    while($row = $result->fetch_object()) {
        echo 'Post ID: ' . $row->ID. ' - Title: ' . $row->post_title. ' Date Uploaded: ' . $row->post_date. '<br>';
    }
   
} else {
    echo 'No Posts Found';
}
$conn->close();

Procedural Approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
$server_name    = 'localhost';
$username       = 'root';
$password       = '';
$db_name        = 'carlofontanos';

$conn = mysqli_connect($server_name, $username, $password, $db_name);

if (!$conn) {
    die('Connection failed: ' . mysqli_connect_error());
}

$sql = 'SELECT * FROM wp_posts WHERE post_type = "post"';
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

    while($row = mysqli_fetch_object($result)) {
        echo 'Post ID: ' . $row->ID. ' - Title: ' . $row->post_title. ' Date Uploaded: ' . $row->post_date. '<br>';
    }
   
} else {
    echo 'No Posts Found';
}

mysqli_close($conn);

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me