目次

mysql_fetch_arrayの添字

mysql_fetch_array関数は引数によって、添字を付けるかどうかなど指定できる
何も引数を指定しなければ、MYSQL_BOTHになる。

引数一覧

MYSQL_ASSOC連想添字(DBキー名)
MYSQL_NUM数値添字
MYSQL_BOTH両方(デフォルト)

MySQL Database

mysql> select * from test;
+----+-----------------+-----------+
| id | ip              | hostname  |
+----+-----------------+-----------+
|  1 | 192.168.1.1     | test1     | 
|  2 | 192.168.1.2     | test2     |
+----+-----------------+-----------+

PHP

$result = mysql_query($sql, $con);
while( $data = mysql_fetch_array($result, MYSQL_BOTH) ){
    print_r($data);
}

結果

MYSQL_BOTH
Array ( [id] => 1 [0] => 1 [ip] => 192.168.1.1 [1] => 192.168.1.1 [hostname] => test1 [1] => test1)
Array ( [id] => 2 [0] => 2 [ip] => 192.168.1.2 [1] => 192.168.1.2 [hostname] => test2 [1] => test2)
MYSQL_ASSOC
Array ( [id] => 1 [ip] => 192.168.1.1 [hostname] => test1)
Array ( [id] => 2 [ip] => 192.168.1.2 [hostname] => test2)
MYSQL_NUM
Array ( [0] => 1 [1] => 192.168.1.1 [1] => test1)
Array ( [0] => 2 [1] => 192.168.1.2 [1] => test2)