William Willi William Willi - 4 months ago 10
SQL Question

How to retrieve values from multiple rows as a single string

I have made MySQL database with three columns

tags_id
,
tags
,
user_id
, it must give out all the tags with respect to the
user_id
given.

eg: for this link:"http://allwaysready.16mb.com/Cuboid/tagsTest.php?user_id[]=7"

Output is:

{"result":[{"tags":"Pascol"},{"tags":"PHP"},{"tags":"Python"}]}


But I need my result to be in a sing string like this:
{"result":[{"tags":"Pascol","PHP",","Python"}]}


It should not be in array i want it in a single string.

Here is my php code :

<?php

if($_SERVER['REQUEST_METHOD']=='GET'){

$user_id = $_GET['user_id'];

require_once('dbConnect.php');

$user_tags = array();

foreach ($_REQUEST['user_id'] as $key => $val) {
$user_tags[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$user_ids = "'" . implode("','", $user_tags) . "'";
$sql = "SELECT * FROM user_tags WHERE user_id IN ({$user_ids})";

$r = mysqli_query($con,$sql);

//creating a blank array
$result = array();

//looping through all the records fetched
while($row = mysqli_fetch_array($r)){

//Pushing name and id in the blank array created
array_push($result,array(
"tags"=>$row['tags']
));
}

//Displaying the array in json format
echo json_encode(array('result'=>$result));

mysqli_close($con);
}


what should i change in my code.?
please help me guys thank you.

Answer

Your array_push mean

Push to your array new element with $key => $value

So solution in this case is remove array_push and try

$result['tags'][] = $row['tags'];
Comments