常用的PHP資料庫操作方法(MYSQL版)

2022-10-03 16:18:10 字數 2605 閱讀 2170

一、資料庫操作

1. 連線mysql資料

mysql_connect()

e.g.

複製** **如下:

$db = mysql_connect(mysql_host, mysql_user, mysql_password) oruzosurfu die(『unable to connect, please check connection paremeters');

2. 選擇資料庫

mysql_select_db()

連線上資料庫後,php預設選擇www.cppcns.com的資料庫未必是我們後面操作中需要的資料庫,為確保資料庫選擇正確,一般在資料庫連線語句後面還要加上資料庫選擇語句。

e.g.

複製** **如下:

mysql_select_db(mysql_db, $db) or die(mysql_error($db));

3. 執行sql語句

mysql_query()

該函式將sql語句傳送到當前活動的資料庫並執行語句,返回結果。

e.g.

複製** **如下:

$query = 「select * from $table」

$result = mysql_query($query, $db) or die(mysql_error($db));

4. 關閉資料庫

mysql_close()

該函式用於關閉不需要繼續活躍的數www.cppcns.com據庫,但該方法不是必須的,一般php會自動關閉不繼續活躍的資料庫。

e.g.

mysql_close($db);

5. 釋放sql結果

mysql_free_result()

該函式用於釋放mysql_query()執行結果占用的記憶體,該函式很少被呼叫,除非result很大,占用太多記憶體;一般在php指令碼執行結束之後很自動釋放占用的記憶體。

二、sql執行結果操作

1. 返回執行結果中的一行

mysql_fetch_row()

返回執行結果的當前行的數值陣列,執行這個函式後,結果指向下一行。

e.g.

$row = mysql_fetch_row($result);

處理執行結果一般放在while迴圈中,遍歷每一行

e.g.

while($row = mysql_fetch_row($result))

2. mysql_fetch_row()的替代方法

mysql_fetch_array()

mysql_fetch_assoc()

mysql_fetch_array()返回鍵值對陣列,鍵為查詢的table的列名;

mysql_fetch_assoc()返回結果時可以先排序(如果為可選引數賦值),相當於mysql_fetch_array()+mysql_assoc

3. 執行結果的字段(列)屬性

mysql_fetch_field()

4. 查詢資料庫中的表名

mysql_list_tables()

e.g.

複製** **如下:

$db_name = mysql_db;

$result = mysql_list_tables($db_name);

echo 「資料庫中包含如下表:」;

while ($row = mysql_fetch_row($result))

5. 查詢資料庫的列名(欄位名)

mysql_list_fields()

e.g.

複製** **uzosurfu如下:

$fields = mysql_list_fields($db_name,$table);

$columns = mysql_num_fields($fields);

for ($i = 0; $i < $columns; $i++)

echo mysql_field_name($fields, $i);

三、其他函式

1. mysql_num_rows()

返回執行結果的行數。

e.g.

$num = mysql_num_rows($result);

2. mysql_num_fields()

返回執行結果的列數(字段數)。

e.g. $num = mysql_num_fields($result);

3.mywww.cppcns.comsql_set_charset()

設定執行結果的編碼,防止在網頁中顯示中文時亂碼。

e.g.

複製** **如下:

$query = 「select * from $table_name」;

mysql_query(『set names utf8′);

$result = mysql_query($query, $db) or die(mysql_error($db));

注: 1. 文中大寫**為預定義的內容,如define(mysql_host, 『localhost');

本文標題: 常用的php資料庫操作方法(mysql版)

本文位址:

php常用鏈結 資料庫操作方法

這篇文章為大家介紹,實用的php 實際開發中常用到的操作mysql資料庫的 段,所有 均可靠執行,此文將持續更新!1 向資料庫插入資料表 con mysql connect 資料庫位址 資料庫使用者名稱 資料庫密碼 建立mysql連線 mysql select db 資料庫名 con 選擇mysql...

SQL資料庫 操作方法

sql資料庫操作方法 執行資料庫語句 public void executesql string strsql 是否有資料 public bool hasdata string tablel 建立資料庫 資料庫名 public void createdatabase string db else c...

Discuz 資料庫操作方法

函式 功能 db table tablename 獲取正確帶字首的表名,轉換資料庫控制代碼 db delete tablename,條件,條數限制 刪除表中的資料 db insert tablename,資料 陣列 是否返回插入id,是否是替換式,是否silent 插入資料操作 db update ...