MySQLi Object Interface in php

The most popular database platform used with PHP is the MySQL database.

Since this object-oriented interface is built into PHP with a standard installation configuration (you just have to activate the MySQLi extension in your PHP environment), all you have to do to start using it is instantiate its class, as in the following code:

$db = new mysqli(host, user, password, databaseName);

Example

$db = new mysqli("localhost", "petermac", "1q2w3e9i8u7y", "library");
$sql = "INSERT INTO books (authorid, title, ISBN, pub_year, available)
 VALUES (4, 'I, Robot', '0-553-29438-5', 1950, 1)";
if ($db->query($sql)) {
 echo "Book data saved successfully.";
}
else {
 echo "INSERT attempt failed, please try again later, or call tech support" ;
}
$db->close();

Retrieving Data for Display

$db = new mysqli("localhost", "petermac", "1q2w3e9i8u7y", "library");
$sql = "SELECT a.name, b.title FROM books b, authors a
 WHERE a.authorid=b.authorid";
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
 echo "{$row['name']} is the author of: {$row['title']}<br />";
}
$result->close();
$db->close();

Leave a Comment