PHP connection MySQL database is through the mysql_connect () function to open a non-persistent MySQL connection.
Grammar:
Mysql_connect (servername, username, password);
Parameter description:
ServerName: Optional. To connect the server name, the default is "localhost:3306", general fill in localhost can.
Username: Optional. User names that log on to the database server are typically root.
Password: Optional. The password to log on to the database server.
Example:
The code is as follows |
Copy Code |
<?php Header ("content-type:text/html; Charset=utf-8 "); $link _id = @mysql_connect (' localhost ', ' root ', ' 123456789 '); if (! $link _id) { Die (' Connect server failed '); } if (! @mysql_select_db (' web ', $link _id)) { Die (' Connection database failed '); } if (! @mysql_query ("Set names ' UTF8 '", $link _id)) { Die (' Set UTF8 format failed '); } Mysql_close (); ?>
|
Example resolution:
Header ("content-type:text/html; Charset=utf-8 ");
The page content is HTML, and the page encoding format is utf-8.
Guaranteed: 1, the Database Code 2, the page code 3, the connection code is consistent, will not appear the garbled phenomenon.
The code is as follows |
Copy Code |
$link _id = @mysql_connect (' localhost ', ' root ', ' 123456789 '); |
Connect the database, and if successful, return a MySQL connection ID to $link _id, and return FALSE for failure. @ is not output to display database error information, to prevent the disclosure of Web site privacy.
The code is as follows |
Copy Code |
if (! $link _id) { Die (' Connect server failed '); } |
To determine whether the database server is connected successfully, the output information "failed to connect to the server" and terminates PHP execution.
The code is as follows |
Copy Code |
if (! @mysql_select_db (' web ', $link _id)) { Die (' Connection database failed '); }
|
To determine whether the server database was successful or unsuccessful, the output information "failed to connect to the database" and terminated PHP execution.
The code is as follows |
Copy Code |
if (! @mysql_query ("Set names ' UTF8 '", $link _id)) { Die (' Set UTF8 format failed '); }
|
Set PHP to connect the MySQL database encoding, not successful, output information "Set UTF8 format failed", and terminate PHP execution.
The code is as follows |
Copy Code |
Mysql_close (); |
Frees the resource, that is, to close the database.
Connect MySQL Database hints
Run code appears: Call to undefined function ' mysql_connect () ' ... Failed
Baidu found the result is Php+mysql environment is not configured well, php5 default MYSQL is closed
Copy Php_mysql.dll and Libmysql.dll files to C:/winnt/system32 (I missed Libmysql.dll)
To find in the php.ini; Extension=php_mysql, remove the front ";" Reboot the server