1

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'];
}
Chaya Cooper
  • 2,566
  • 2
  • 38
  • 67

4 Answers4

1

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.

Don Dickinson
  • 6,200
  • 3
  • 35
  • 30
  • I really wish that SO gave me the option of accepting more than one answer. You definitely gave me the clearest explanation of what was causing the problem, and I'm always torn when I have to decide between the best answer and the one that I learned the most from – Chaya Cooper Apr 17 '13 at 05:49
1

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

$first_names[] = $row['first_name'];
prodigitalson
  • 60,050
  • 10
  • 100
  • 114
1

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.

Aditya
  • 2,148
  • 3
  • 21
  • 34
  • That did it :-D Out of curiosity, would you mind explaining the 1rst method? I'm wondering if that might cut out a step by allowing me to define the array and use it in the same statement? – Chaya Cooper Apr 17 '13 at 02:35
  • This is there in the manual http://php.net/manual/en/function.array-push.php. You will still need an array as you have to extract the values of your column from each row. – Aditya Apr 17 '13 at 02:49
  • Thank you :-) I'm still really learning about arrays :-) Is there a benefit to one method over the other, or is it just personal preference? – Chaya Cooper Apr 17 '13 at 02:50
  • The second way is better for single elements, as we avoid the overhead of a method call. But i don't think its much of a difference. I prefer the first way as i think it makes for easier reading, but its just personal preference. – Aditya Apr 17 '13 at 02:54
  • you are welcome. Please mark the answer you found most appropriate as correct! – Aditya Apr 17 '13 at 03:26
1

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 :)

Community
  • 1
  • 1
Rixhers Ajazi
  • 1,303
  • 11
  • 18
  • Thanks for the suggestion :-) I'm curious about you comment about try/catch - I'm actually structuring the connection like that in the config file (which is why I'm using $conn->), but I was told that I should also surround each db query with a try/catch. Is that unnecessary? – Chaya Cooper Apr 17 '13 at 02:33
  • 1
    Well like it was stated on my post here and the ones I linked, the only reason you want to surround them in a try/catch is if you wan't to do something else if a query goofs up on you. For instance if you want to log them in a special log file or what have you. The query will either fail or not fail... so that part the EXCEPTION Mode will handle. – Rixhers Ajazi Apr 17 '13 at 02:35
  • Just to put it into context, if say you want to do a try/catch and if it fails you want an email to send to you, then yes a try/catch will be great for this... but if you just want to check if the query is a go then just let the default error handling do the trick for you. – Rixhers Ajazi Apr 17 '13 at 02:39
  • I'm not sure if I'm following you 100%, but I believe that you're confirming what I initially thought (before getting yelled at several times on SO ;-) ) - that since there's a try/catch statement in the config file it automatically gets called every time I call that function. Am I correct about that? – Chaya Cooper Apr 17 '13 at 02:39
  • Can I see your config file - any important information. I am not 100% sure if that will be the case. – Rixhers Ajazi Apr 17 '13 at 02:41
  • Based on this reading http://php.net/manual/en/class.pdoexception.php if you do a try/catch in the config file it will only cause an exception of the connection itself has failed... – Rixhers Ajazi Apr 17 '13 at 02:42
  • Sure :-D try{ $conn = new PDO('mysql:host=xxxxx;dbname=xxxxxxxx', 'username', 'password'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage(); } – Chaya Cooper Apr 17 '13 at 02:46
  • Okay then yes that will only give an exception if the connection fails as based off the link I posted above your connection information. – Rixhers Ajazi Apr 17 '13 at 02:47
  • I'm a little lost now ;-) Should I be doing it differently? – Chaya Cooper Apr 17 '13 at 02:48
  • No your fine, my initial comment was that if your not leaving customized messages, sending yourself emails, etc. etc. then you do not need to have try/catch on all your queries. Try/Catch should be implemented if you need a custom action if the query fails. You config is fine! Just trying to help you write less code is all :) Sorry for confusing you :*( – Rixhers Ajazi Apr 17 '13 at 02:52
  • I was just losing track of how it all tied together ;-) I'm all about finding shortcuts :-D And since I'm not creating customized messages right now it sounds like I just found one :-) – Chaya Cooper Apr 17 '13 at 02:54
  • Thats awesome! Just as a little bit of extra context I use Try/Catch once (as of now before I did all the time) and that one instance is on a email if the query fails... so yea I'm glad that its clear now. Also is your first issue fixes with the array stuff? – Rixhers Ajazi Apr 17 '13 at 02:56
  • Now the only question is how to post my code in the future so that I won't get reamed each time? (Every time I didn't bother including it I'd get at least 2 lectures about the need for try/catch, error messages, etc. :-( ) – Chaya Cooper Apr 17 '13 at 02:57
  • (sigh) Different people have different ways. I've lately cut out all the try/catch's on my models in my code. If anything you can just link to the two posts I linked you or just link to this for future reference. oooorrrr....... just add "snippets" of your code and not actually show them that you are not using try/catch :P – Rixhers Ajazi Apr 17 '13 at 02:59
  • That's actually what I was doing (only including snippets), which is why it got so frustrating. Maybe I'll be lucky and people will ease up on me now that I have more points ;-) I LOVE the SO community, but sometimes it can be a bit difficult or intimidating – Chaya Cooper Apr 17 '13 at 03:02
  • Yes very, I also love when we get the random -1 and no one says anything... (face-palm). I have no points :( – Rixhers Ajazi Apr 17 '13 at 03:03
  • 1
    What cracked me up was when I answered my own question and it got a -1 :-D How is that even possible? – Chaya Cooper Apr 17 '13 at 03:04