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 ...