Skip to content
Advertisement

Separating specific MySQL columns from row fetch into another array in php

What I am trying to do is get back the 5 recent announcements in my announcements table. After that, I am trying to separate the announcementText column data into another array with each row in its own index, and for each index, I would like to echo that out on the HTML page. The code, however, does a weird split of the row data. Sometimes it’s one character per index, and sometimes multiple characters, but it’s never the whole message. The table schema is as follows:

JavaScript

The result I get from the final array (varies depending on announcement):

JavaScript

The result I get from the database:

JavaScript

What I expected is to have the announcement show correctly in its entirety.

Here is my code so far:

JavaScript

Advertisement

Answer

You’re using PDO’s fetch() (which only returns one single record) instead of fetchAll() (which returns all matched records).

Try doing something like this:

JavaScript

As you can see in the above code, I removed the $announcementText-array and one of the foreach, since they basically just iterate through the same data.

Note: I also changed how the HTML is outputted. I tend to recommend against echoing a bunch of HTML through PHP since it makes it much harder to debug (no syntax highlighting in PHP strings, for example.)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement