Mysql_connect () function
Definition and usage
The mysql_connect () function opens a non-persistent MySQL connection.
Syntax
Mysql_connect (server, user, pwd, newlink, clientflag)
Example
| The code is as follows: |
Copy code |
<? Php $ Con = mysql_connect ("localhost", "mysql_user", "mysql_pwd "); If (! $ Con) { Die ('could not connect: '. mysql_error ()); } // Some code... Mysql_close ($ con ); ?> |
Next let's look at a database connection instance.
Create a database named test (using phpadmin) as shown in the following figure:
Then, create a table named "user" in the table,
The preparation is complete and the process starts :)
| The code is as follows: |
Copy code |
<? Php // Connect. php $ Db_server = "localhost"; // database server name $ Db_user = "root"; // User name used to connect to the database $ Db_pwd = "leaf"; // database connection password $ Db_name = "test"; // database name $ Db = mysql_connect ($ db_server, $ db_user, $ db_pwd, $ db_name ); /* Object-oriented $ Db = new mysql ($ db_server, $ db_user, $ db_pwd, $ db_name ); */ If (! $ Db) echo "fail "; Else echo "connect success" ?> |
If PHP is a version later than 4.0, you can use the mysqli library and write the corresponding code as follows:
| The code is as follows: |
Copy code |
<? Php ...... $ Db = mysqli_connect ($ db_server, $ db_user, $ db_pwd, $ db_name ); /* Object-oriented $ Db = new mysqli ($ db_server, $ db_user, $ db_pwd, $ db_name ); */ If (mysqli_connect_errno ()){ Echo "Error: cocould not connect to database. Please try again laer ."; Exit; } Else echo "Success! "; ?> |
Note: The function library mysqli is used, so you need to open extension = php. mysqli in the php. Ini file.
Generally, we place the lines before the code in a preparation file. Here we name it db_config.php.
| The code is as follows: |
Copy code |
<? Php // Db_config.php $ Db_server = "localhost"; // database server name $ Db_user = "root"; // User name used to connect to the database $ Db_pwd = "leaf"; // database connection password $ Db_name = "test"; // database name ?> |
In this way, the initial connection test code becomes like this:
| The code is as follows: |
Copy code |
<? Php // Connect. php Require_once ("db_config.php"); // contains the configuration file $ Db = mysql_connect ($ db_server, $ db_user, $ db_pwd, $ db_name ); // You can also use the object-oriented syntax. If (! $ Db) echo "fail "; Else echo "connect success" ?> |