I really can’t find a way to print the content of the array on a page. Can anyone help?
I have taken the data from a database and looped it into an javascript array and now would like to just display it on the page for now.
Here is the code:
<html>
<head>
<script>
var items = {
<?php
$con = mysql_connect("***","****","*****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("learning_game", $con);
$result = mysql_query("SELECT * FROM data");
$first=true;
while($row = mysql_fetch_array($result))
{
if (!$first){
echo ",";
}
$first = false;
echo "{name='" . $row['word'] . "',image='" . $row['image'] ."'}";
}
mysql_close($con);
?>
};
</script>
</head>
<body>
</body>
</html>
Please note, that the
itemsdeclaration is now with[]signs, so it becomes an array, not an object.In the line where you echo out the name and image the equals signs became colons (:).
As well as the full script had to be moved to the bottom, because you can only write into elements which are already rendered (closed). So I have added a new
divinto the mix, and write into that.