Forum und email

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5, PECL mysql:1.0)

mysql_fetch_assoc — 연관 배열로 결과 행을 반환

설명

array mysql_fetch_assoc ( resource $result )

인출된 행을 연관 배열로 반환하고, 내부 데이터 포인터 바로 앞으로 이동한다. mysql_fetch_assoc()은 두번째 선택 인자로 MYSQL_ASSOC를 이용하여 mysql_fetch_array()를 호출하는 것과 동일하다. 이 함수는 연관 배열만을 반환한다.

매개변수

result

mysql_query() 호출을 통한 결과 resource.

반환값

인출된 행에서 연관 배열을 반환하거나 더 이상의 행이 없다면 FALSE를 반환한다.

동일한 이름을 포함하는 둘 또는 그 이상의 컬럼들은 마지막 컬럼이 우선권을 가질 것이다. 동일한 이름의 다른 컬럼에 접근하기 위해서는 mysql_fetch_row()를 사용하거나, 별명(alias)을 사용하면 된다. mysql_fetch_array()의 별명에 대한 설명은 예제를 참조하라.

예제

Example#1 mysql_fetch_assoc() 예제

<?php

$conn 
mysql_connect("localhost""mysql_user""mysql_password");

if (!
$conn) {
    echo 
"Unable to connect to DB: " mysql_error();
    exit;
}
  
if (!
mysql_select_db("mydbname")) {
    echo 
"Unable to select mydbname: " mysql_error();
    exit;
}

$sql "SELECT id as userid, fullname, userstatus 
        FROM   sometable
        WHERE  userstatus = 1"
;

$result mysql_query($sql);

if (!
$result) {
    echo 
"Could not successfully run query ($sql) from DB: " mysql_error();
    exit;
}

if (
mysql_num_rows($result) == 0) {
    echo 
"No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row mysql_fetch_assoc($result)) {
    echo 
$row["userid"];
    echo 
$row["fullname"];
    echo 
$row["userstatus"];
}

mysql_free_result($result);

?>

주의

Note: 성능 mysql_fetch_assoc()mysql_fetch_row()보다 느려지지는 않는다.

Note: 이 함수가 반환하는 필드 이름은 대소문자를 구별합니다.

Note: 이 함수는 NULL 필드를 PHP NULL 값으로 설정합니다.