Skip to Main Content
Upgrading to PHP 5
book

Upgrading to PHP 5

by Adam Trachtenberg
July 2004
Intermediate to advanced content levelIntermediate to advanced
350 pages
10h 9m
English
O'Reilly Media, Inc.
Content preview from Upgrading to PHP 5

Object-Oriented Interface

The mysqli extension also allows you to manipulate the data using an object-oriented interface. Everything that can be done using the procedural interface is available this way. Here is the same sample transaction from the last section translated into the OO style:

$mysqli = new mysqli('db.example.org', 'web', 'xyz@123');
$mysqli->select_db('users');

$result = $mysqli->query("SELECT username FROM users");

while ($row = $result->fetch_assoc( )) {
    print $row['username'] . "\n";
}

$result->close( );

With the OO interface, there’s no need to pass database handles as the first parameter to a mysqli method. Instead, the extension stores that handle as part of the mysqli object.

If you’re porting code from mysql and use the default link option, you may find it easier to switch to the OO syntax because it doesn’t require you to modify the argument list of every mysql function.

You can also use mysqli_init( ) and mysqli_real_connect( ):

$mysqli = new mysqli( );
$mysqli->init( );
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 120);
$mysqli->options(MYSQLI_OPT_LOCAL_INFILE, false);

$mysqli->real_connect('db.example.com', 'web', 'xyz@123', 'users', 
                       3306, NULL, MYSQLI_CLIENT_COMPRESS);

A new mysqli object does not automatically call mysqli_init( ) in its constructor. This is still your responsibility.

Certain mysqli functions are object properties instead of methods, in particular, mysqli_error( ), mysqli_errno( ), and mysqli_insert_id( ). Here’s an example using ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert PHP and MySQL®

Expert PHP and MySQL®

Andrew Curioso, Ronald Bradford, Patrick Galbraith
Pro PHP Programming

Pro PHP Programming

Peter MacIntyre, Brian Danchilla, Mladen Gogala
Mastering PHP 7

Mastering PHP 7

Branko Ajzele

Publisher Resources

ISBN: 0596006365Supplemental ContentCatalog PageErrata