Changing From mysql_ Functions to mysqli_

Here are the similarities and differences I noticed when switching from the mysql_ prefixed functions to the mysqli_ functions in PHP.

Creating a Connection

Creating and closing a connection are exactly the same using mysqli_:

// Creating a Connection with mysql_connect()
$conn = mysql_connect($servername, $username, $password);

// Do stuff with database here.

// Close the Connection
mysql_close($conn);

////////////////////////////////////

// Creating a Connection with mysqli_connect()
$conn = mysqli_connect($servername, $username, $password);

// Do stuff with database here.

// Close the Connection
mysqli_close($conn);

Connecting to a Database

Connecting to a database can actually be done with one less step with mysqli_:

// Connecting to a Database with mysql_connect() and mysql_select_db()
$conn = mysql_connect($servername, $username, $password);
$db = mysql_select_db($database, $conn);

// Do stuff with database here.

// Close the Connection
mysql_close($conn);

////////////////////////////////////

// Connecting to a Database with mysqli_connect()
$conn = mysqli_connect($servername, $username, $password, $database);

// Do stuff with database here.

// Close the Connection
mysqli_close($conn);

Getting a Single Value With mysqli_

// Connecting to a Database with mysqli_connect()
$conn = mysqli_connect($servername, $username, $password, $database);

// Getting a Single Value Using mysqli_fetch_array and mysqli_query
$user_id = mysqli_fetch_array(mysqli_query($conn, "SELECT `user_id` FROM `user_ids` WHERE `user_email` = 'user-email@example.com';"));
if ( ($user_id[0] !== '') && !(empty($user_id[0])) ) {
	$user_id = $user_id[0];
} else {
	return "Error selecting user.";
}

// Close the Connection
mysqli_close($conn);

Please Note: To keep the post simple, I left out error reporting. If you are interacting with a database, it is important to include a fallback for if a connection fails or a database cannot be connected to using a function like this: die( ‘Could not connect to mysqli: ‘ . mysqli_error() );

Further Reading

W3Schools
StackOverflow Answer