Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON to get info from a database

Tags:

json

php

mysql

Dear fellow Coders/Hacker/Programmers all around. I am in need of some help. I am using the code below to get Info from my MySQL database. This is the PHP code:

<?php
ini_set("display_errors", true);
ini_set("html_errors", false);
require "conn.php";
$query=mysqli_query($conn,"SELECT * FROM UserData");

if ($query){
    while($row=mysqli_fetch_array($query)){
        $flag[] =$row;


    }
    print(json_encode($flag));


}
mysqli_close($conn);
return $flag;
?>

This is what my database has:

id|username|password|likedOne|likedTwo|likedThree|likedFour|likedFive
1 |NetsGets|Test    |        |        |          |         |

The code prints this:

{"0":"1","id":"1","1":"netsgets","username":"netsgets","2":"test","password":"test","3":"","likedOne":"","4":"","likedTwo":"","5":"","likedThree":"","6":"","likedFour":"","7":"","likedFive":""}

I want it to be like this:

{"id":"1","username":"netsgets","password":"test","likedOne":"","likedTwo":"","
likedThree":"","likedFour":"","likedFive":""}

(Like it should be!!!)

Please help me with fixing this.


1 Answers

Assuming connection works and it fetches data correctly, you can use mysql_fetch_assoc instead:

<?php
ini_set("display_errors", true);
ini_set("html_errors", false);
require "conn.php";
$query=mysqli_query($conn,"SELECT * FROM UserData");

if ($query){
    while($row=mysqli_fetch_assoc($query)){
        $flag[] =$row;


    }
    print(json_encode($flag));


}
mysqli_close($conn);
return $flag;
?>

I personally would move to PDO if you have the option though as it allows you a better database abstraction

like image 163
Youn Elan Avatar answered Dec 10 '25 11:12

Youn Elan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!