I have a simple php code, which retrieves info from a database, and stores it in a multi dimensional array:
<?php
//Fetches the mediainfo entries to populate the webpage, up to as many are in the DB.
error_reporting(E_ALL);
$db = new mysqli("localhost","root","pass", "Media");
if($db->connect_errno > 0){
echo "ERROR";
die('Unable to connect to database [' . $db->connect_error . ']');
}
$data_array=array();
$sql = "SELECT * FROM mediainfo;";
// echo $sql;
$result = mysqli_query($db,$sql);
if($result && mysqli_num_rows($result) > 0){
$row=mysqli_fetch_all($result,MYSQLI_ASSOC);
mysqli_close($db);
for($i = 0; $i < count($row);$i++){
$data_array[$i][0] = $row[$i]['ID'];
$data_array[$i][1] = $row[$i]['IMGPATH'];
$data_array[$i][2] = $row[$i]['TITLE'];
$data_array[$i][3] = $row[$i]['RATING'];
$data_array[$i][4] = $row[$i]['POSITION'];
}
//echo $data_array[0][0];
return $data_array;
if(!empty($data_array))
{
$data_array[0][0] = "ERROR";
return $data_array;
}
else{
$data_array[0][0] = "ERROR";
return $data_array;
}
}
else{
$error[0][0] = "error";
return $error;
}
//$JSONString = json_encode($data_array);
// return $data_array;
?>
Ignore the redundant array fillings, that was just me testing values.
The js is:
function loadMedia(){
console.log("please work");
$.post("getMedia.php",
{
success: function(data){
console.log(data[0][0]);
}})
}
I'm just trying to print the first element of the first row, to see if it exists. Currently it simply prints 'undefined'. If anyone could provide any insight it would be greatly appreciated.
I'd just like to stress that I DO know that the array is full when I return it. Thanks
Update So following some quick responses(thanks) I've tried the following:
if($result && mysqli_num_rows($result) > 0){
$row=mysqli_fetch_all($result,MYSQLI_ASSOC);
mysqli_close($db);
$JSONString = json_encode($row);
return $JSONString;
and:
<script>
function loadMedia(){
console.log("please work");
$.post("getMedia.php",
{
success: function(data){
console.log(data);
}})
}
</script>
Unfortunately it has the same result.
Second update So I've added header('Content-type: application/json.');, and upon explicitly calling the php file with a button, a download is launched for the JSON string. Progress! The php won't run automatically from my AJAX call though. Or rather, it still returns undefined.