Miljan Ilic
Miljan Ilic

Reputation: 335

Listing MySQL Array in HTML Table

Ihave one script to list data from MySQL in HTML Table. Inserting in MySQL is dynamical and each category have diffrent number of fields. Because data is dynamicaly inserted in MySQL table Content I have record for each FiledContent. Now when I'm selecting data I have non splited array data and in HTML table I'm getting one content field for all records. I want to spit records from Content and get splited Content for each Field Name in HTML Head Table.

With this script:

$sql = "SELECT FieldContent FROM Content JOIN Fields ON Content.ForField = Fields.FieldName WHERE Fields.ForUser = 'Viruss' AND Fields.ForCategory = 'Otpornici'";
    if ($result = $conn->query($sql)) {
        while($row = $result->fetch_assoc()) {
        echo "<th>".$row["FieldContent"]."</th>";       
    }      

I'm getting this as result:

enter image description here

Upvotes: 0

Views: 408

Answers (1)

cjds
cjds

Reputation: 8426

That's because you're using the <th> tag wrong.

<th> stands for table header, so the table will continue producing headers instead of rows. You need to use the <tr> tag to make a table row.

$sql = "SELECT FieldContent FROM Content JOIN Fields ON Content.ForField = ...";
if ($result = $conn->query($sql)) {
    while($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>$row["FieldContent"]['testcontent1']</td>";
        echo "<td>$row["FieldContent"]['testcontent2']</td>";
        echo "<td>$row["FieldContent"]['testcontent3']</td>";
        echo "</tr>";    
    }   
}   

You should also use the <td> tag to represent table data.


Now you have to split your content into multiple rows. It is NOT recommended you store data like this. You can do comma separated values or another method

while($row = $result->fetch_assoc()) {
     echo "<tr>";
     $split = explode(' ', $row["FieldContent"]); // Split up the whole string
     $chunks = array_chunk($split, 3); // Make groups of 3 words
     $result = array_map(function($chunk) { return implode(' ', $chunk); }, $chunks);
     foreach($result as $value)
          echo "<td>$value</td>";
      echo "</tr>";    
}

Upvotes: 1

Related Questions