Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

php - PDO returning incorrect, but duplicate, data. Key's not in database.

I'm new to using $pdo statements so might be something simple I haven't yet read on php.net. I'm receiving duplicate results when querying the database.

Result:

[0] => Array
    (
        [umeta_id] => 31
        [0] => 31
        [user_id] => 2
        [1] => 2
        [meta_key] => fbmeta
        [2] => fbmeta
        [meta_value] => someMetaValueStuff;
        [3] => someMetaValueStuff;
    )

The query is quite simple:

function getData(){
    global $pdo;
    $query = $pdo->prepare('SELECT * FROM usermeta WHERE meta_key = "fbmeta" LIMIT 0,30');
    $query->execute();

    return $query->fetchAll();
}

print_r( getData() );

The problem is that the named keys (umeta_id, user_id, meta_key, meta_value) DO exist, the numeric keys do not. How come the query returns these? And how do I prevent them from even being returned?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not duplicates, it's just the current FETCH_MODE you're using. To get as associative keys only you need to specify as such; by default it fetches as both.

Use like so:

$query->fetchAll(PDO::FETCH_NUM); // to fetch with numeric indexes
$query->fetchAll(PDO::FETCH_ASSOC); // to fetch with associative indexes

fetchAll docs
fetch docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...