I have a MySQL query that I pass to a PHP array. The PHP array is turned into a JSON array using json_encode
. I am trying to then get this to print onto my html page. Here is what I have so far.
<?php
class db {
public $conn;
function dbLogin() {
$this->conn = new mysqli("1.2.3.4","user","pwd","db");
}
public function selectQuery() {
$this->dbLogin();
$query = "
SELECT *
FROM tekken_7_frame_data
";
echo "<pre>";
$resultArray = Array();
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_array()) {
$resultArray[] = $row;
}
}
echo "</pre>";
$resultJson = json_encode($resultArray);
}
}
$fData = new db();
$fData->selectQuery();
?>
<html>
<head>
</head>
<body>
<script>
var jsonArray = <?php echo $resultJson ?>;
document.write(jsonArray);
for (i = 0; i < jsonArray.length; i++) {
document.write(jsonArray[i][1]);
}
</script>
</body>
</html>
I've read up on other similar questions on StackOverflow with no luck; my html page is completely blank. I've tried placing json_econde(...)
inside of the javascript variable jsonArray
instead of in my PHP class. That didn't work either. I have also var_dump
'd the PHP array with no issue (the whole thing displayed on the page), as well as placed the array in a PHP variable using json_encode
, then echoed that array with no issue.
I have no idea how to access this JSON array. I ultimately want it in a table, but because this is my first time bridging the gap between PHP and Javascript, I figured that I would take it one step at a time so that I know exactly what is going on.
var_dump
'd the PHP array with no problem. I have placed the PHP array into a variable usingjson_encode
, then printed that variable with no problem either. Both arrays display on the page in full. No errors in the console when I display both arrays either.$resultJson
variable that appears within the function, and then over in the JS part, also. I'd recommend you edit your function to NOT echo a<pre>
, and to return the array. And then you'll have something like$result = $db->selectQuery();
, and thenecho $result;
.for
loop. It should bei < jsonArray.length
, noti > jsonArray.length
. This is causing the loop to end immediately without printing anything.