programing

PDO 쿼리가 결과 집합의 각 필드를 두 번 반환합니다.

nicegoodjob 2023. 1. 26. 11:33
반응형

PDO 쿼리가 결과 집합의 각 필드를 두 번 반환합니다.

내가 해결할 수 없는 가장 이상한 문제가 있다.결과의 각 필드를 두 번 반환하는 간단한 MySQL 쿼리가 있습니다.첫 번째 키는 필드 이름이고 두 번째 키는 정수입니다.

표는 다음과 같습니다.

id int(11)
user_id int(11)
first_name varchar(255)
last_name varchar(255)
country_code varchar(3)
mobile varchar(255)
email varchar(255)
profile_img var_char(255)
timestamp timestamp

코드는 다음과 같습니다.

$db = new PDO('mysql:host=localhost;dbname=proj', 'dev', '<password>');
$sql = "SELECT * FROM contact";
$stmt = $db->prepare($sql);
$stmt->execute();
$contacts = $stmt->fetchAll();
print_r($contacts));

출력은 다음과 같습니다.

Array
(  
[id] => 1  
[0] => 1  
[user_id] => 1  
[1] => 1  
[first_name] => joan  
[2] => joan  
[last_name] => smith  
[3] => smith  
[country_code] => AU  
[4] => AU  
[mobile] => 0400 222 333  
[5] => 0400 222 333  
[email] => joan@example.com  
[6] => joan@example.com  
[profile_img] =>   
[7] =>  
[timestamp] => 0000-00-00 00:00:00  
[8] => 0000-00-00 00:00:00  
)

Debian 9.1 VM에서 MariaDB 15.1과 PHP 7.0을 사용하고 있습니다.

이것은, 유저가 유저에 대해서fetch_style파라미터$stmt->fetchAll();디폴트로는 PDO는 번호부 키와 관련 키(예: "first_name" 및 2)를 모두 가진 배열로 결과를 가져옵니다.

문서에서:

fetch_style

에 기재되어 있는 대로 반환되는 어레이의 내용을 제어합니다.PDOStatement::fetch(). 디폴트값:PDO::ATTR_DEFAULT_FETCH_MODE(디폴트는PDO::FETCH_BOTH)

연관 인덱스만 가져오려면 매개 변수를 전달하십시오.PDO::FETCH_ASSOC와 같이

$contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);

번호가 매겨진 인덱스만 가져오려면 매개 변수를 전달하십시오.PDO::FETCH_NUM와 같이

$contacts = $stmt->fetchAll(PDO::FETCH_NUM);

모든 옵션세트는 의 매뉴얼에 기재되어 있습니다.

언급URL : https://stackoverflow.com/questions/56052432/pdo-query-is-returning-each-field-twice-in-the-result-set

반응형