1

How can I fetch all the values from columns (like an id column) and put them into an array?

I'm using PDO API and I tried with other code, but it's not working for me.

$STH = $DBH->query('SELECT Tid  from Playlist ');
$STH->setFetchMode(PDO::FETCH_OBJ);
$result = $STH->fetch();

while($result = mysql_fetch_array($result)) {
    $ids_array[] = $result['Tid'];
}
2
  • 2
    You are mixing mysql_* with PDO ?! Commented May 16, 2015 at 6:35
  • yes i just tried with this way :p i don't have more idea about mysql i just tried to use this code Commented May 16, 2015 at 6:37

2 Answers 2

8

You can directly return an id array by specifying the PDO::FETCH_COLUMN.

$stmt = $DBH->query("SELECT Tid from Playlist");
$ids_array = $stmt->fetchAll(PDO::FETCH_COLUMN);
Sign up to request clarification or add additional context in comments.

Comments

3

You are mixing mysql_* and PDO, which is obviously not going to work.

Just fetchAll() your results and then just merge all rows into one array by simply looping through all rows with array_map() and returning the id, e.g.

$stmt = $DBH->query("SELECT Tid  from Playlist");
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$ids = array_map(function($v){
    return $v->Tid;
}, $result);

print_r($ids);

2 Comments

thanks , but there is a syntax error in your code . it's not working and i have no idea about array map to solve it by my self
@user44444 Just reload the page again. Just missed a curly bracket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.