加油啊,親愛的學員!從這一週開始,我們就要透過PHP程式碼操控MySQL資料庫了。MySQL是PHP支援最完整的"關聯式資料庫管理系統(RDBMS)",也是我們透過PHP認識"關聯式資料庫管理系統"共通特性以及練習SQL語法的絕佳工具,請各位學員務必熟悉每一個環節,瞭解每一個步驟所代表的意義。
在"關聯式資料庫管理系統(RDBMS)"中,除了系統管理專用的資料庫之外,資料庫系統可以同時管理許多個別的資料庫。系統管理者可以透過"使用者群組"的控管,授權使用者在特定的名稱與密碼之下操作特定的個別資料庫。這些控管是透過之前提過的DCL_data control language所掌控,比較偏向資料庫管理員的領域,我們就不多加著墨。你只要記得,你是透過資料庫使用者名稱與密碼的授權來使用某一特定資料庫的,這三個特定資料,請自行牢記!
要透過PHP程式碼操作MySQL資料庫,首先,一定得先和MySQL資料庫系統取得連線,這就像我們要到銀行保險箱存取物件時,得先取得進入保險庫的資格一樣;進入保險庫後,接著,你才可以根據你的權限開啟相關的保險箱;最後,再透過特定的方式,執行一段(SQL)指令,進行保險箱內容的存取(新增、刪除、修改、查詢)。
練習範例如下:
一. 新增資料表:
<?php
// Connecting database server
$link = mysql_connect('Remote_server', 'User_Name', 'Password')
or die('Could not connect: ' . mysql_error());
echo 'MySQL Connected successfully...';
// selecting database
mysql_select_db('Database_Name', $link)
or die('Could not select database.');
echo 'Database selected successfully...';
// Assigning DDL-SQL query to a local variable
$query = 'create table classmates ('
. ' cid int unsigned not null auto_increment primary key,'
. ' cname char(10) not null,'
. ' cnick char(10),'
. ' cmail char(50) not null )';
// Performing DDL-SQL query to create table
mysql_query($query, $link)
or die('Could not create table: ' . mysql_error());
echo 'Table created successfully...';
// Closing connection
mysql_close($link);
?>
二. 資料表資料新增:
<?php
// Connecting database server
$link = mysql_connect('Remote_server', 'User_Name', 'Password')
or die('Could not connect: ' . mysql_error());
echo 'MySQL Connected successfully...';
// selecting database
mysql_select_db('Database_Name', $link)
or die('Could not select database.');
echo 'Database selected successfully...';
// Assigning DML_INSERT_SQL query to a local variable
$query = "insert into classmates (cname, cnick, cmail)"
. " values ('姓名', '暱稱', '信箱');"
// Performing SQL query
mysql_query($query) or die('Query failed: ' . mysql_error());
echo 'Data inserted successfully';
// Closing connection
mysql_close($link);
?>
三. 資料查詢與顯示:
<?php
// Connecting database server
$link = mysql_connect('Remote_server', 'User_Name', 'Password')
or die('Could not connect: ' . mysql_error());
echo 'MySQL Connected successfully...';
// selecting database
mysql_select_db('Database_Name', $link)
or die('Could not select database.');
echo 'Database selected successfully...';
// Assigning DML_SELECT_SQL query to a local variable
$query = 'select * from classmates';
// Performing SQL query to get a resultset
$result = mysql_query($query, $link)
or die('Query failed: ' . mysql_error());
// Printing results in a HTML table
echo "<table border=1>\n"; // \n as Enter_newline
// Use while & foreach to survey the resultset
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n"; // \t as Tab
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset first
mysql_free_result($result);
// Closing connection at last
mysql_close($link);
?>
留言列表