0

I'm building a REST API and I don't know how to echo several values from one column, I want to echo several values from one single column to a JSON array like the example below. The column will be used to store the usernames a users friends. How do I echo this as the example below and how do I store it in the mysql using PHP?

{
   "friends":[
       "tim",
       "jesper",
       "wexx"
   ]
}

1 Answer 1

1

This is how to get the values from MySQL and convert them to JSON format

$conn = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$db = mysql_select_db(DB_DATABASE) or die(mysql_error());


// get the info from the db 
$sql = "SELECT names FROM friends ORDER BY id";
$result = mysql_query($sql, $conn) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)){
    $output[]=$row;
} 

print(json_encode($output));
Sign up to request clarification or add additional context in comments.

7 Comments

I get the respone: [ { friends: "frej, jack" } ] How can I make one array for each user?
That's weird, they should be in an array. Can you send me some screenshot how are the results ordered in your MySQL?
@TimLilleSkuttBillström, here is a demo of an API I've made before using the same script link and a screenshot of my PhpMyAdmin: link. Can you see the diffrence?
No I cant haha, tell me? @ninjaprog
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.