当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > 连接 MySQL
The free MySQL Database is very often used with PHP.
PHP经常与MySQL数据库搭配使用。
Before you can access and work with data in a database, you must create a connection to the database.
在你访问和运行数据库中的数据时,你首先必须与数据库建立一个连接。
In PHP, this is done with the mysql_connect() function.
在PHP中,我们使用mysql_connect()函数来建立连接。
mysql_connect(servername,username,password); |
Parameter 参数 | Description 描述 |
---|---|
servername | Optional. Specifies the server to connect to. Default value is "localhost:3306" 可选参数。指定需要连接的服务器。默认值为:localhost:3306 |
username | Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process 可选参数。指定登陆的用户名。默认的用户名是对数据库拥有操作权的用户的名称。 |
password | Optional. Specifies the password to log in with. Default is "" 可选参数。指定登陆的密码。默认值为:""(空) |
Note: There are more available parameters, but the ones listed above are the most important. Visit our full PHP MySQL Reference for more details.
注意:上面列举的项都是非常关键的。下面列举一些其它可使用的参数。具体请访问我们的PHP MySQL 参数。
In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails:
下面的案例当中,我们将数据库的连接保存在一个变量($con)中,目的是为了今后对脚本的使用;如果这个连接失败,那么将执行"die"中的内容:
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?> |
The connection will be closed as soon as the script ends. To close the connection before, use the mysql_close() function.
当脚本结束时,连接自动关闭。我们使用mysql_close()函数来关闭连接,具体如下:
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?> |