串連到 MySQL 資料庫
建立一個串連到MySQL資料庫
在您可以存取資料庫中的資料,您必須建立一個串連到資料庫。
在PHP中,這一點與mysql_connect ( )函數。
文法
mysql_connect(servername,username,password);
| Parameter |
Description |
| servername |
Optional. Specifies the server to connect to. Default value is "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 "" |
註:有更多的可用參數,但上面列出的是最重要的。訪問我們充分的PHP MySQL的參考更詳細的資訊。
例如
在下面的例子中,我們儲存串連在一個變數( $控制)以供日後使用的指令碼。該“死”的一部分將被處死,如果串連失敗:
<?php$con = mysql_connect("localhost","peter","abc123");if (!$con) { die('Could not connect: ' . mysql_error()); }
// some code
?>
關閉串連
串連將自動關閉時,指令碼的目的。要關閉串連之前,請使用mysql_close ( )函數:
<?php$con = mysql_connect("localhost","peter","abc123");if (!$con) { die('Could not connect: ' . mysql_error()); }
// some code
mysql_close($con);?>