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).
I want to select the entire table's ctg
column(a total of at most 20 rows) into an array with integer indexes.
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.
id ctg
01 movie
27 tv
64 sports
etc.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With