0

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.

2
  • Remove array_push and try this $result[tags][] = $row['tags']; Commented Jul 31, 2016 at 9:19
  • {"result":[{"tags":"Pascol","PHP",","Python"}]} ? its not even a valid json string, you mean {"result":[{"tags":"Pascol,PHP,Python"}]}? Commented Jul 31, 2016 at 9:37

1 Answer 1

1

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'];
Sign up to request clarification or add additional context in comments.

2 Comments

but after adding this code tags is considered to be an array . i want to be remain as string only .
Your result "tags":"Pascol","PHP",","Python" must use array do it. I'm sorry about late reply.

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.