Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL PDO fetchAll as array with integer index

I have a table with two columns. Table: ctgtable and columns: id and ctg. Since I am entirely moving from previous mysql_* functions to PDO, I am facing some foolish mistakes(or maybe lack of knowledge).

Question

I want to select the entire table's ctg column(a total of at most 20 rows) into an array with integer indexes.

My Method

The nearest possible solution in my opinion was this:

<?php
    $sth = $dbh->prepare("SELECT id, ctg FROM ctgtable");
    $sth->execute();
    /* Fetch all of the values of the second column */
    $result = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
    var_dump($result);
?>

Is there any other shorter/better alternative for the same result? Or this is the best/only possible method to fetch results.

Sample Table

id      ctg
01     movie
27       tv
64     sports

etc.

Sample Result

Array( 1 => "tv",
    2 => "movie",
    3 => "anime",
    4 => "game",
    5 => "telugu"
);

The indexing may or may not start from 0. It doesn't matter to me. I tried searching for such a possible question, but none of them seemed relevant to my question.

like image 977
hjpotter92 Avatar asked Sep 15 '12 16:09

hjpotter92


1 Answers

The method you have is fine. Though if you don't need the ID, why would you need to query it?

<?php
    $sth = $dbh->prepare("SELECT ctg FROM ctgtable");
    $sth->execute();
    /* Fetch all of the values in form of a numeric array */
    $result = $sth->fetchAll(PDO::FETCH_ARRAY);
    var_dump($result);
?>

Less constraints on the MySQL leads to less processing time, which eventually leads to better results.

like image 188
Madara's Ghost Avatar answered Sep 22 '22 19:09

Madara's Ghost