通過php腳本建立與一個mysql數(shù)據(jù)庫的連接時,數(shù)據(jù)庫服務(wù)器的主機位置(在本地就是localhost)、用戶名(root)、密碼、和數(shù)據(jù)庫名是必須的。一旦建立連接,腳本就能執(zhí)行sql命令。
二者之間的連接使用的步驟主要分為四步:
1、用mysqli_connect()連接數(shù)據(jù)庫;
2、組裝sql查詢串,放入一個變量,該變量將作為下一步的必須參數(shù);
3、用mysqli_query()執(zhí)行查詢,
4、用mysqli_close()關(guān)閉連接。
下面深入分析
一、 mysqli_connect():建立連接,語法
mysqli_connect(server,user,passwd,database_name);該函數(shù)將位置,用戶名,口令,數(shù)據(jù)庫名處理為串,所以必須用引號引起,例如:
$dbc = mysqli_connect('localhost','root','password','aliendatabase');調(diào)用該函數(shù)可以得到一個數(shù)據(jù)庫連接,另外會得到一個php變量$dbc,這個變量與數(shù)據(jù)庫交互。
注:1、php語句要用分號結(jié)束。
2、使用’localhost’,是代表數(shù)據(jù)庫服務(wù)器和web服務(wù)器在同一個服務(wù)器計算機上。
3、如果省略第四個參數(shù),會用mysqli_select_db()來指定數(shù)據(jù)庫名;
4、如果連接失敗,die()函數(shù)會終止php腳本,并提供失敗代碼的反饋,例如
$dbc = mysqli_connect('localhost','root','password','aliendatabase') or die('error connecting to mysql sever.');如果連接未能創(chuàng)建就調(diào)用die()函數(shù),反饋消息會輸出到頁面上,同時注意兩個函數(shù)之間(即or前面)不需要分號,因為這是同一條語句的延續(xù)。
二、建立php串變量,它包含所要執(zhí)行的sql查詢語句,比如增、刪、建等,例如建立一個insert查詢:
$query = insert into aliens_abduction(first_name, last_name, .
when_it_happend, how_long, how_many, alien_description, .
what_they_did ,fang_spotted, other, email) .
values ('sally', 'jones', '3 days ago', '1 day',’four‘, .
'green with six tentacles', 'we just talked and palyed with a dog' , .
'yes', 'i may have seen your dog .contact me.', .
'sa'
);代碼說明:1. $query是一個php串變量,現(xiàn)包含一個insert查詢;
2. 點號”.”告訴php將這個串與下一行串聯(lián)在一起;
3. 整個代碼是php代碼,必須以分號結(jié)束。
insert查詢存儲在一個串中之后,可以將它傳遞到mysqli_query()函數(shù)
注: 1、“查詢”含義相當廣義,可以指在數(shù)據(jù)庫上完成的任何sql命令,包括存儲和獲取數(shù)據(jù);
2、php 中 sql 查詢語句使用雙引號
3、在 sql 查詢語句中的字符串值必須加引號
4、數(shù)值的值不需要引號
5、null 值不需要引號
三、利用php查詢mysql數(shù)據(jù)庫
mysqli_query()函數(shù)需要兩個信息來完成查詢:數(shù)據(jù)庫連接(第一步)和sql查詢串(第二步),例如:
$result = mysqli_query($dbc,$query);
or die('error querying database.');$result 變量只是存儲mysqli_query()執(zhí)行的查詢是否成功。
四、用mysqli_close()關(guān)閉連接,參數(shù)為一開始簡歷的數(shù)據(jù)庫連接變量,例如:
mysqli_close($dbc);