0

I am doing a web service in php to encode data to json. My php code is:

    function getProgramDay($day)
{

    global  $DDBB_SERVER, $DDBB_USER, $DDBB_PASSWORD, $DDBB;



    $sql = "SELECT program.id, programa.name FROM `mybd` WHERE program.day = '" . $day . "'";


    $con = mysqli_connect($DDBB_SERVER, $DDBB_USER, $DDBB_PASSWORD, $DDBB);

    if (!$con) {
        die('Error de Conexión (' . mysqli_connect_errno() . '): ' . mysqli_connect_error());
    }

    if (!mysqli_set_charset($con, "utf8")) {
        die("Error loading character set utf8:" . mysqli_error($con));
    }

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

    $res = array();

    // Prepare data
    while ($row = mysqli_fetch_assoc($result)) {
        $res[] = $row;
    }

    // Free resultset
    mysqli_free_result($result);

    // Close connection
    mysqli_close($con);

    // Return data
    return $res;

}

And the result of this function in json is:

[{"id":"1","nombre":"Hello"}]

I would like that the result will be:

{"results":[{"id":"1","nombre":"Hello"}]}

How can I do this? I have tried but not works:

return "{'results':" .$res . "}";

Thank you so much :-)

3
  • but can´t do it with my example code? Thanks Commented Jun 3, 2014 at 13:06
  • 2
    warning your code might be vulnerable to sql injection attacks! Commented Jun 3, 2014 at 13:06
  • 1
    $res['results'][] = $row; Commented Jun 3, 2014 at 13:06

2 Answers 2

6
return json_encode(array("results"=>$res));

As said in the comment, if you want to return an array and create the json in the calling code, do it like this:

return array("results"=>$res);
Sign up to request clarification or add additional context in comments.

3 Comments

I expect that json_encode is called in the calling code (as he says he gets json), so he should not do it twice, just return the php array
Thanks, it puts "{\"results\": and using json validator it says that is not valid json, how can I quit this \? Thank you so much
@Igor thats because you are using json_encode twice - do as per the amended code above (or see my comment to your question)
0

Your output

 [{"id":"1","nombre":"Hello"}]

is an array (witch you build with) // Prepare data while ($row = mysqli_fetch_assoc($result)) { $res[] = $row; }

What you want to have is an an object

object(stdClass)#6 (1) { ["results"] => array(1) { [0] => object(stdClass)#7 (2) { ["id"] => string(1) "1" ["nombre"] => string(5) "Hello" } } }

so change your Prepare data with mysqli_fetch_object and use json_encode

Comments

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.