PHP DBH->fetch() and fetchAll(), there is a way to get rid of "numbered" items in the returned arrays?

238 views Asked by At

I copy and paste the example from one PHP docs page, 'cause the case is similar: when I execute a MySQL query using DBH->fetch() I obtain an array:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

The output will be:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [name] => pear
            [0] => pear
            [colour] => green
            [1] => green
        )

    [1] => Array
        (
            [name] => watermelon
            [0] => watermelon
            [colour] => pink
            [1] => pink
        )
)

There is a way to tell the driver to return only "named" array elements and removing the ones with numeric indexes? Something like:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [name] => pear
            [colour] => green
        )

    [1] => Array
        (
            [name] => watermelon
            [colour] => pink
        )
)

Thanks in advance, Simone

1

There are 1 answers

0
Gregory Hart On

The Fetch_Assoc returns the named array only. Here is your code with the change.

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetch_assoc();
print_r($result);
?>