本文涵蓋錯誤訊息取得、增強版陣列擷取、欄位中繼資料物件、以及單列各欄位長度資訊四大實用函數群。
string mysql_error([resource link_identifier])
<?php
$link = mysql_pconnect("localhost", "user", "pass") or die("連線失敗");
$query = "SELECT * FROM president";
$result = mysql_query($query) or die("查詢失敗:" . mysql_error());
?>
array mysql_fetch_array(int result [, int result_type])
result_type 選項:
MYSQL_ASSOC:僅關聯索引(同 mysql_fetch_assoc)MYSQL_NUM:僅數字索引(同 mysql_fetch_row)MYSQL_BOTH:預設,兩者皆有AS。mysql_fetch_row 相近。<?php
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
// 數字索引
printf("%s %s<br>", $row[0], $row[1]);
// 關聯索引
printf("%s %s<br>", $row["last_name"], $row["first_name"]);
}
mysql_free_result($result);
?>
object mysql_fetch_field(int result [, int col_num])
name、type、max_length、primary_key、not_null 等)。col_num 時依序推進;指定時可隨機存取。| 屬性 | 說明 |
|---|---|
| name | 欄位名稱 |
| table | 所屬資料表 |
| type | 資料類型 |
| max_length | 最大長度 |
| not_null | 是否 NOT NULL |
| primary_key | 是否主鍵 |
| unique_key | 是否唯一鍵 |
| multiple_key | 是否非唯一索引 |
| numeric | 是否數值型 |
| blob | 是否 BLOB/TEXT |
| unsigned | 是否無號數 |
| zerofill | 是否 ZEROFILL |
<?php
for ($i = 0; $i < mysql_num_fields($result); $i++) {
$meta = mysql_fetch_field($result, $i);
if (!$meta) continue;
echo "<pre>";
foreach ($meta as $key => $val) {
printf("%s: %s<br>", $key, $val);
}
echo "</pre>";
}
?>
array mysql_fetch_lengths(int result)
mysql_fetch_row() 擷取的那一列,各欄位值的實際字串長度(位元組數)。false。<?php
while ($row = mysql_fetch_row($result)) {
$lengths = mysql_fetch_lengths($result);
for ($i = 0; $i < count($row); $i++) {
printf("Column %d: 值='%s' 長度=%d<br>", $i, $row[$i], $lengths[$i]);
}
}
?>
mysql_fetch_array(MYSQL_BOTH) 是最通用的擷取方式;mysql_error() 是除錯生命線;mysql_fetch_field() 提供完整結構描述,適合建立動態表單或匯出工具。再次提醒:新專案請改用 mysqli/PDO。