Mysqli and Object-Oriented PHP

Sometimes it is easy for me to get stuck doing things the way I know how to do it, rather than finding a better, more up-to-date method. I just had a recent post about making multiple connections to mysql, but just in the last week, I’ve learned a better way to do it. I’m a little behind in learning this stuff, but I’m sure there are others out there like me.

Mysqli stands for Mysql Improved. It came out a while ago, I believe with Mysql 4.1.3 and up. There are a lot of great benefits to using mysqli, which I won’t get into now. Maybe later. Here’s just a little to get you started using it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
 
// Connect to Database
$db = new mysqli('host', 'username', 'password', 'database');
 
// Perform a query
$items = $db->query("SELECT * FROM cp_items WHERE id > 100");
 
// Run a loop through the results
while($item = $items->fetch_object()) {
    echo '<ul>';
    echo '<li>' . $item->id . '</li>';
    echo '<li>' . $item->name . '</li>';
    echo '</ul>';
}

Connecting to multiple databases at the same time is simple. Just create a new database object, and call the mysqli functions from it. You can read the full documentation of everything available with mysqli to learn more about it.

This entry was posted in MySQL, PHP. Bookmark the permalink.

Comments are closed.