MySQLi Tutorial


Moving from a procedural system to object-oriented can be a daunting task. One feature to assist you is the MySQLi class, which allows for an object-oriented approach to database manipulation. This tutorial gives insight into the structure and basic usage of the MySQLi class. If PDO isn’t an option for you, then try MySQLi!

MySQLi stands for MySQL Improved, and is available from MySQL versions >= 4.1.3 and must be compiled in PHP with –with-mysqli=/path/to/mysql/bin/mysql_config.

There are three hierarchical classes with MySQLi:

  1. mysqli – Represents a connection between PHP and a MySQL database
  2. mysqli_stmt – Represents a prepared statement
  3. mysqli_result – Represents the result set obtained from a query against the database

Each one of these classes represent a different situation. The mysqli class is absolutely necessary because you will be communicating only through this class. It contains the connection to the other two classes (mysqli_stmt and _result). For instance, if you were executing a SELECT statement to pull cities from the states table, you would do something like the following:

$mysqli = new mysqli('hostname','username','password','database');
//This is where we will query the database and pull using the cities/states SELECT statement
// If the result returns true
if ($result = $mysqli->query("SELECT city FROM state WHERE state='AL'")) {
// So the result returned true, let's loop and print out each city.
// The number of rows returned is assigned to the property "num_rows" in the mysql_result class
echo 'For the state of AL, there are '.$result->num_rows.' cities.
// The "fetch_object()" method is the equivalent of the old mysql_fetch_object() function. It allows access to the returned rows within the resouce object ($result in this case).
while ($row = $result->fetch_object()) {
echo 'City Name: '.$row->city.'
} else {
// Notice below that the errors are still contained within the mysqli class. This means that each result will affect a single "error" property. In otherwords, if your result fails, the error returned from MySQL is assigned to the property "error".
// This means the query failed
echo $mysqli->error;
} // end else

Before we go any further, let’s look at each one of the methods and parameters of the mysqli and mysqli_result class. This tutorial will not cover the mysql_stmt class, as this will be “Part 2″, which will cover prepared statements, and will be available within the next week.

Part 3 of the mysqli tutorial will cover transactions using the InnoDB engine.

mysqli Class Methods:

  • mysqli – construct a new mysqli object

  • autocommit - turns on or off auto -commiting database modifications

  • change_user - changes the user of the specified database connection

  • character_set_name - returns the default character set for the database connection

  • close - closes a previously opened connection

  • commit - commits the current transaction

  • connect - opens a new connection to MySQL database server

  • debug - performs debugging operations

  • dump_debug_info - dumps debug information

  • get_client_info - returns client version

  • get_host_info - returns type of connection used

  • get_server_info - returns version of the MySQL server

  • get_server_version - returns version of the MySQL server

  • init - initializes mysqli object

  • info - retrieves information about the most recently executed query

  • kill - asks the server to kill a mysql thread

  • multi_query - performs multiple queries

  • more_results - check if more results exist from currently executed multi -query

  • next_result - reads next result from currently executed multi -query

  • options - set options

  • ping - pings a server connection or reconnects if there is no connection

  • prepare - prepares a SQL query

  • query - performs a query

  • real_connect - attempts to open a connection to MySQL database server

  • escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection

  • rollback - rolls back the current transaction

  • select_db - selects the default database

  • set_charset - sets the default client character set

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

  • stmt_init – initializes a statement for use with mysqli_stmt_prepare

  • store_result - transfers a resultset from last query

  • thread_safe - returns whether thread safety is given or not

  • use_result - transfers an unbuffered resultset from last query

mysqli Class properties:

  • affected_rows - gets the number of affected rows in a previous MySQL operation

  • client_info - returns the MySQL client version as a string

  • client_version - returns the MySQL client version as an integer

  • errno - returns the error code for the most recent function call

  • error - returns the error string for the most recent function call

  • field_count - returns the number of columns for the most recent query

  • host_info - returns a string representing the type of connection used

  • info - retrieves information about the most recently executed query

  • insert_id - returns the auto generated id used in the last query

  • protocol_version - returns the version of the MySQL protocol used

  • server_info - returns a string that represents the server version number

  • server_version - returns the version number of the server as an integer

  • sqlstate - returns a string containing the SQLSTATE error code for the last error

  • thread_id - returns the thread ID for the current connection

  • warning_count - returns the number of warnings generated during execution of the previous SQL statement

The best way to explain the usage of the mysqli class is to show by example. There are too many methods and properties to go over in this tutorial, so I will only give examples of some.

It’s important to note that some of these methods listed, aren’t methods at all. For instance, if you wanted to get the client library version of MySQL, you would use mysqli_get_client_version(), which returns the integer version. Here is an example:

printf("Client version: %d\n", mysqli_get_client_version());

You are forced to use the functions since there is no need for the connection to the actual database.

You have already seen the usage of the mysql_result connection from the mysqli class, so let’s go over some more examples:

Getting some info on the result from the mysql database:

$mysqli = new mysqli('localhost','db_user','my_password','mysql');
// Get all the MySQL users and their hosts
$sql = "SELECT user, host FROM user";
// If the query goes through
if ($result = $mysqli->query($sql)) {
// If there are some results
if ($result->num_rows > 0) {
// Let's show some info
echo 'There were '.$result->num_rows.' rows returned.
echo 'We selected '.$result->field_count.' fields in our query.
echo 'Our thread ID is '.$mysqli->thread_id.'
// Ok, let's show the data
while ($row = $result->fetch_object()) {
echo 'Username: '.$row->user.' :: Host: '.$row->host.'
} // end while loop
} else {
echo 'There are no results to display. Odd how we connected to this database and there are no users.';
} // end else
} else {
// Notice the error would be within the mysqli class, rather than mysql_result
printf("There has been an error from MySQL: %s",$mysqli->error);
} // end else
// Close the DB connection

Here we used some common methods and properties to test and display information. Next week we will go over prepared statements and how they might assist in your scripts.

If you have any questions regarding MySQLi, please feel free to put comments and I will answer them soon.

– Will

Labels: ,
Loading related posts...


Post a Comment

2010 WEBSITE20. All rights reserved.