Concrete-Cowboy
Concrete-Cowboy

Reputation: 87

How to convert arrays from PHP/MySQL to Javascript

I am having difficulty with getting the JavaScript portion of this code to work the way I would like.

I have managed to pull the array from a MySQL table and convert it using JSON.

However, when I try to get the data into a HTML table, I get individual characters in each cell.

For example, my database has a table with a keyword labels. Inside this are 4 colors Blue, Green, Brown, Hazel exactly as I have entered it here.

When I output via JavaScript, I get one character in each cell instead of 4 cells.

I am "almost" there on my own:

<?php
include 'conn.php';
$sql = "SELECT * FROM variables WHERE id= '1' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $labels = $row["labels"];
    }
    foreach (explode(',', $labels) as $newLabel) {
        echo "{$newLabel} ";
    }
} 
?>
<script>

<?php $newLabel = $labels ?>
var n = <?php print (json_encode($newLabel)); ?>;
var index;
var myTable= "<table class='hover'>";


myTable+= "<tr><td class='smalltd'style='width: 20px; font-weight:bold;'></td>";
for (index = 0; index < newLabel.length; index++) {
    myTable+= "<td class='no' style='width: 100px; font-weight:bold;'>" 
           + newLabel[index] + "</td>";
}

myTable+="</table>";

document.write(myTable);
</script>

I suspect the culprit lies in the newLabel.length but I am not certain

Upvotes: 1

Views: 81

Answers (1)

vaso123
vaso123

Reputation: 12391

First of all, you need to collect your labels into an array, not a string:

$labels[] = $row["labels"];

Second, you've never defined the newLabel javascript variable. Change

for (index = 0; index < newLabel.length; index++) {

to

for (index = 0; index < n.length; index++) {

and use n or rename n to newLabel

Upvotes: 1

Related Questions