First, connect the database:
Method 1.
<?php
$mysqli =new mysqli (' localhost ', ' mysql_user ', ' mysql_pwd ', ' use_db_name ');
?>
Method 2.
<?
$mysqli =new mysqli ();
$mysqli =>connect (' localhost ', ' mysql_user ', ' mysql_pwd ');
$mysqli =>select_db (' mysql_db_name ');
?>
Second, you cannot set any MySQL-specific connection options when establishing a connection using the Mysqli construction method. To set connection options, you can use Mysqli_init () to create a connection
<?php
/* Create a Connection object using Mysqli_init () */
$mysqli =mysqli_init ();
$mysqli->options (Mysqli_init_command, ' SET autocommit=0 '); Successful connection execution ' SET autocommit=0 '
$mysqli->options (mysqli_opt_connect_timeout,5); Sets the time in seconds for the connection to time out
$mysqli->real_connect (' localhost ', ' mysql_user ', ' mysql_pwd ', ' my_db_name ');
?>
Mysqli_connect_errno () test for errors during connection, use the Mysqli_connect_error () function to return error messages
<?php
$mysqli =new mysqli (' localhost ', ' mysql_user ', ' mysql_pwd ', ' dbname ');
/* Check the connection if the connection error output error message and exit the program */
if (Mysqli_connect_errno ()) {
printf (' Connection failed:%s\n ', Mysqli_connect_error ());
Exit ();
}
?>
Iv. after completing the database access work, you should close the connection release related Mysqli objects in time.
Although all open database connections are closed automatically after the execution of the script, the resource is recycled.
However, during execution, it is possible that the page requires multiple database connections, and each connection is closed at the appropriate time.
The close () method in the Mysqli object is responsible for closing the Open database connection, returning true on success, or false
<?php
/* Connect to MySQL database and return mysqli object successfully */
$mysqli =new mysqli (' localhost ', ' mysql_user ', ' mysql_pwd ', ' mysql_db_name ');
/* Check for errors in connection */
if (Mysqli_connect_errno ()) {
printf ("Connection Failed:%s<br>", Mysqli_connect_error ());
Exit ();
}
/* Print current database using character set String */
printf ("The character set for the current database is:%s<br>", $mysqli->character_set_name ());
/* Print Client version */
printf ("Current client version is:%s<br>", $mysqli->get_client_info ());
/* Print Server host information */
printf ("Host information:%s<br>", $mysqli->host_info);
/* Print an integer form MySQL server version */
printf ("Server version:%d<br>", $mysqli->server_version);
/* Close Open database connection */
$mysqli->close ();
?>
Connection and shutdown of the database