Chaya Cooper
Chaya Cooper

Reputation: 2530

This foreach statement is only adding last row to the array

How can I change this foreach statement so that it will build an array with all the rows in the particular column? It's currently only adding the last row in column 'first_name' to the array.

try {  
    $stmt = $conn->prepare("SELECT * FROM student");  
    $stmt->execute();
} catch(PDOException $e) {
    echo $e->getMessage();
} 
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$first_names = array();
foreach ($rows as $row) { 
  $first_names = $row['first_name'];
}

Upvotes: 1

Views: 295

Answers (4)

Rixhers Ajazi
Rixhers Ajazi

Reputation: 1313

You have to add brackets your variable `

$first_names[] = $row['first_name'];`

Also may I suggest a bit cleaner method in doing this?

You seem to be using try/catch in you queries and probably use it on most of them as well...

You should in fact be using

$pdo = new PDO("mysql:host=xxxxx;dbname=xxxxxxxx", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // < - - - THIS

so that now you won't need to be adding try/catch to your code.

Usually you would only need to use try/catch if you wan't to do something else if the query fails.

read up on this here and here

Enjoy :)

Upvotes: 1

Aditya
Aditya

Reputation: 2246

you can try this

array_push($first_names, $row['first_name']);

or

$first_names[] = $row['first_name'];

The problem in your code is that you are overwriting your own variable again and again.

Upvotes: 1

prodigitalson
prodigitalson

Reputation: 60413

Youre currently overriting the variable you need to stuff it in the array:

$first_names[] = $row['first_name'];

Upvotes: 1

Don Dickinson
Don Dickinson

Reputation: 6248

You forgot the brackets. You need to do this:

$first_names[] = $row['first_name'];

otherwise, you're re-creating the $first_names variable as a single string and overwriting it with each iteration of the loop.

Upvotes: 1

Related Questions