tags:

views:

98

answers:

4

Hello everyone. MySQL connection in PHP can be established in two ways:

$mysql = new mysqli('localhost', 'user_name', 'password', 'database_name');

or

$link = mysqli_connect('localhost', 'user_name', 'password');
mysqli_set_charset($link, 'utf8');
mysqli_select_db($link, 'database_name');

Which one is better?

+2  A: 

Will you be dealing with more than one database? If so it might be a good idea not to set the database_name in the constructor. Otherwise, no problem. Other than the fact that you set the charset in the second one I don't think there's much of a difference.

RobbR
+3  A: 

Whichever one you prefer. I would go with the OOP Interface for consistency with the rest of my application, because that's how I use MySqli. Also, in my opinion, the OOP interface way is much cleaner (aesthetically, at least).

karim79
+1  A: 
if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
  // error: mysqli extension error
  exit('...');
}

$connection = mysqli_init();
@mysqli_real_connect($connection, DBHOST, 
  DBUSER, DBPASS, DBNAME, DBPORT, NULL, MYSQLI_CLIENT_FOUND_ROWS);

if (mysqli_connect_errno() > 0) {
  // error: connection error
  echo mysqli_connect_error();
  exit();
}

// Force UTF-8.
mysqli_query($connection, 'SET NAMES "utf8"');

This sample according to Drupal6 database.mysqli.inc

RayZ
+1  A: 

Connecting using the mysqli extension gives you the ability to use newer MySQL features such as transactional queries and parameterised queries which aren't available using the older mysql extension.

Have a look at http://www.php.net/manual/en/book.mysqli.php

RMcLeod