Home >Backend Development >PHP Tutorial >Detailed explanation of PHP connection to mysql database test example_PHP tutorial
If you want php to be able to connect to mysql on our homepage, you must know that php needs to enable the mysql module in php.ini. The specific opening method will be introduced later in the article. Let's look at the example test of php connecting to mysql.
PHP connects to the MySQL database through the mysql_connect() function to open a non-persistent MySQL connection.
Grammar:
mysql_connect(servername, username, password);
Parameter description:
servername: optional. The name of the server to be connected, the default is "localhost:3306", generally fill in localhost.
username: optional. The user name used to log in to the database server is usually root.
password: optional. Password to log in to the database server.
Example:
The code is as follows | Copy code | ||||||||||||||||||||
$link_id = @mysql_connect('localhost', 'root', '123456789'); if (!$link_id) { Die('Failed to connect to server');
}
if (!@mysql_query("set names 'utf8'", $link_id)) { Die('Failed to set utf8 format');
mysql_close();
|
The code is as follows | Copy code |
$link_id = @mysql_connect('localhost', 'root', '123456789'); |
The code is as follows | Copy code |
if (!$link_id) { Die('Failed to connect to server'); } |
The code is as follows | Copy code |
if (!@mysql_select_db('web', $link_id)) { Die('Failed to connect to database'); } |
The code is as follows | Copy code |
if (!@mysql_query("set names 'utf8'", $link_id)) { Die('Failed to set utf8 format'); } |
Set the encoding for PHP to connect to the MySQL database. If unsuccessful, the message "Failed to set UTF8 format" will be output and the execution of PHP will be terminated.
The code is as follows
|
Copy code
|
||||
mysql_close(); Release resources, that is: close the database.
Prompts for connecting to mysql database Running code appears: Call to undefined function 'mysql_connect()'... failed |
http: //www.bkjia.com/PHPjc/630688.html