First, if PHP wants to operate the database, the first thing to do is to establish a connection with the database. Usually we use the mysql_connect function to connect to the database. This function needs to specify the address, user name and password of the database.
$host = 'localhost';
$user = 'code1';
$pass = '';
$link = mysql_connect($host, $user, $pass);
The way PHP connects to the database is similar to directly using the command Connect through the following line, similar to: mysql -hlocalhost -ucode1 -p. When the connection is successful, we need to select an operating database and select the database through the mysql_select_db function.
mysql_select_db('code1');
Usually we will first set the character encoding used by the current connection. Generally, we will use utf8 encoding.
mysql_query("set names 'utf8'");
Through the above steps, we have established a connection with the database and can perform data operations.
Second, the difference between mysql_select_db(); select database function and MySQLi:
mysql_select_db and mysqli_select_db parameter order is reversed
mysql_select_db(database,$conn)
mysqli_select_db($conn,database)
Function parameters:
database required. Specifies the database to be selected.
$conn is optional. Specifies the MySQL connection. If not specified, the previous connection is used.
Three, send query instructions to the database in the form of sql statements.
$res = mysql_query('select * from user limit 1');
For query class statements, a resource handle (resource) will be returned, and the data in the query result set can be obtained through this resource.
$row = mysql_fetch_array($res);
var_dump($row);
By default, PHP uses the nearest database connection to execute the query, but if there are multiple connections, you can query from that connection through the parameter command .
$link1 = mysql_connect('127.0.0.1', 'code1', '');
$link2 = mysql_connect('127.0.0.1', 'code1', '', true); //Open a new connection
$res = mysql_query('select * from user limit 1', $link1); //Query data from the first connection
The above introduces the process of connecting PHP to the MySQL database, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.