0

I have tried researching other questions similar to my problem, but I haven't found anything that addresses this specifically. I am selecting data using mysqli and displaying it in a table. The column table_yard can have multiple values, so I exploded those values and stored them as an array to be looped through and then stored the result in variable $yard_name. I later assign this variable to a row in my table like so ($get is storing the sql query):

 while ($row = mysqli_fetch_assoc($get)) {
    $yards = explode(",", $row[table_yard]);
foreach ($yards as $yard) {
    $yard_name = $yard . ", ";
}
    $table_rows .= "<tr>
                <td>" . mdy($row[table_date]) . "</td>
                <td>" . $yard_name . "</td>
                </tr>";

The problem is, if there is more than one value in that array, it only displays the first item. I ran a debug on $yards to see if it was even getting all the values of the array, and it is, as shown here:

Array (
[0] => 711
[1] => 2793
[2] => 988
)

Although, this is what gets displayed in the <td> cell:

711, 

What I want it to display is this:

711, 2793, 988 

I am sure it's a rookie mistake, but I can't figure it out. Thank you in advance for any help.

7
  • 1
    You're overwriting the $yard_name variable with every loop of the foreach Commented Jan 26, 2015 at 22:22
  • why do you don't use $yard_name = implode(", ", explode(",", $row[table_yard])); Commented Jan 26, 2015 at 22:28
  • $yard_name .= $yard . ", "; Commented Jan 26, 2015 at 22:32
  • But its showing 711, or 988,? Commented Jan 26, 2015 at 22:34
  • @Bankzilla Aha! I knew it was something simple. Thank you so much! Commented Jan 26, 2015 at 22:58

1 Answer 1

2

Untested but this should help fix the issue. Defining $yard_name before the loop so it doesn't get constantly overwritten

while ($row = mysqli_fetch_assoc($get)) {
    $yards = explode(",", $row[table_yard]);
    $yard_name = "";
    foreach ($yards as $yard) {
        $yard_name .= $yard . ", "; // Add to the string instead of overwriting
    }
    $table_rows .= "<tr>
        <td>" . mdy($row[table_date]) . "</td>
        <td>" . trim($yard_name, ",") . "</td>
    </tr>";
}
Sign up to request clarification or add additional context in comments.

Comments

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.