Reputation: 3468
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?
Upvotes: 16
Views: 5782
Reputation: 93
seems to do the trick for me. Put this on top
use Illuminate\Database\Events\StatementPrepared;
when ever fetching include pdo::fetch_assoc
return($pdo->fetchAll(\PDO::FETCH_ASSOC));
Upvotes: -1
Reputation: 1482
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
Upvotes: 25
Reputation: 30488
This is not duplicate data fetchAll
returns data in numeric array as well as associative array.
See the Docs
Use this for retrieving only associative array
return $query->fetchAll(PDO::FETCH_ASSOC);
Upvotes: 10