I want to pass the results of a query to javascript (I want to make an interactive quiz about fish species). This seems to be easy with json_encode, but the structure of my php array makes it difficult to access? Even console.log
does not work, so there is probably an error, though I have been checking this code more than i would like to admit. I am pretty sure the error is in the small javascript part though. The code (this is all in a .php file):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<?php
$con = new mysqli("localhost", "root", "", "marinefish");
$query = "SELECT Commonname, Scientificname FROM allseafish";
$result = $con->query($query);
while ($row = $result->fetch_array()){
$rows[] = $row;
}
/*
Structure rows:
array(544) {
[0]=>
array(4) {
[0]=>
string(7) "Allfish"
["Commonname"]=>
string(7) "Allfish"
[1]=>
string(11) "Omni pisces"
["Scientificname"]=>
string(11) "Omni pisces"
}
*/
mysqli_free_result($result);
mysqli_close($con);
?>
<title>Untitled</title>
</head>
<body>
<script type="text/javascript">
var ars = <?php echo json_encode($rows) ?>;
console.log(ars);
alert(ars[0][0]);
</script>
</body>
</html>
Any suggestions, or easy-to-understand links/ tutorials are very welcome!
I tried: http://www.dyn-web.com/tutorials/php-js/json/multidim-arrays.php which seems very clearly explained, but couldn't help me. I also have tried to simplify the structure of the php array, but without success.
And I tried to change the echo json_encode($rows)
into print(json_encode($rows))
.
As you may have noticed, I am new with this, so all basic tips will be a great help.
Thank you!