简体   繁体   中英

The best way to connect MySQL database in PHP

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 the better and why?

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

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.

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

The best way to connect to MySQL database in PHP is using PDO driver , http://php.net/manual/es/book.pdo.php also you have parametrized query and you can avoid SQL injection easily and other features you may love, also you may know that is prepared to work with object-oriented programming , which it's pretty cool .

PS : PDO also can be used to connect to other kinds of SQL databases, like SQL Server, etc. You have to learn PDO (it's simple) and then you can connect to many kinds of SQL databases.

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

Both approaches are valid ways to use the mysqli extension. The first is the object-oriented interface and the second is the procedural interface. They are equivalent and it is simply a matter of preference. See the PHP mysqli documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM