1

hey there im a little stuck with getting data from my phpmyadmin and displaying it as json this is my php so far

<?php

$user = '';
$password = '';
$con=mysqli_connect("localhost",$user,$password,"tugutept_jumputi");
if (mysqli_connect_errno())
  {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$query = 'SELECT * FROM chartable';


$stm = mysqli_query($con,$query);

$data_array = array();
$count = 0;
while($r = mysqli_fetch_row($stm)){
    $data_array[$count] = $r;
    $count= $count +1;

}
echo json_encode($data_array);
mysqli_close($con);


?>

which displays this the outputted json when i want it looking like this

[
  {
    "ID": "000001"
    "Name": "[The Saiyan who grew up on Earth] Son Goku",
    "Portrait": "BaseGoku.png",
    "Series": "Dragon Ball",
    "MaxRarity": "6 start",
    "Type": "Blue",
    "Class": "Tank",
    "Era": "1980",
    "Release Date": "2018-03-28",
    "Farmable": "0",
    "Method": "Trade Medal Store"
  }
]

i want to take each row from the table and put it in an array but i keep getting the whole table in one array, as you can see im a little stumped any help is welcome thanks

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mrtcupz
  • 37
  • 6
  • You must use foreach. – Simone Rossaini Jan 28 '20 at 07:17
  • yes, Iterate ( loop ) your data to create your exact array. – Shashank Shah Jan 28 '20 at 07:18
  • thanks i have been trying to put a foreach loop but i keep getting a 500 error not to sure if this is correct – Mrtcupz Jan 28 '20 at 17:38
  • $query = 'SELECT * FROM chartable'; $stm = mysqli_query($con,$query); $data_array = array(); $count = 0; foreach($data_array as $v){ $data_array[$count] => $v; $count= $count +1; } echo json_encode($data_array); mysqli_close($con); – Mrtcupz Jan 28 '20 at 17:38
  • Please read https://stackoverflow.com/questions/58808332/should-we-ever-check-for-mysqli-connect-errors-manually – Dharman Jan 28 '20 at 21:22
  • Could you please update the question to show us what changed you have made. Could you also explain what exactly the issue is? I don't understand it from the description. – Dharman Jan 28 '20 at 21:23
  • Just changed the while loop to a foreach loop but i cant get it to work – Mrtcupz Jan 28 '20 at 22:35

1 Answers1

0

At the moment, you are fetching the data with a numeric index using mysqli_fetch_row() - which says from the manual

Get a result row as an enumerated array

As the json_encode() sees a sequential numeric array starting at 0, it will encode it as an array and not an object.

If you want the column names, change that to mysqli_fetch_assoc()...

while($r = mysqli_fetch_assoc($stm)){

Which says

Fetch a result row as an associative array

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55