Need json_encode output in array having a index :How to do this ...

Need a output which show success flag with index of all the values from test table
here is the code ! How to do ? and get web service showing the complete output in an array having index = 1

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydb";

 //$something = $_GET['s'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}else{
          //echo "Success";

}

 
$jsonObj =  array();

$sql = "SELECT *   FROM test ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        //echo "id: " . $row["id"]. " - Name: " . $row["Data"]. " " . $row["Data"]. "<br>";

             $jsonObj[] = $row;
             //$jsonObj[] = array($row);

    }
} else {
    echo "0 results";
}

        
    echo json_encode($jsonObj);  

Need a output which show success flag with index of all the values from test table

//header('Content-type: application/json');
//$final_res = json_encode($jsonObj,JSON_FORCE_OBJECT);
//echo  $final_res ;



$conn->close();
?>
Puneet AroraFounderAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Does your code work or not?  What is the value of $jsonObj before json_encode() is called?  You can use var_dump() to find this data.
0
Puneet AroraFounderAuthor Commented:
Dear Ray , My Code does work ! , But I need output  as an array and object both ..
I either get it as array or object ,

I need out put which is array having a "object ". The object has values from table "test " and the object name should be like "success"
0
Puneet AroraFounderAuthor Commented:
Dear Ray

an out put like : {
    "success": 1,
    "test_table": [
        {
            "id": "1",
            "Data1": "SomeData",
            "Data2": "Some Data 300.00",
            "Data3": "Some Data XX",
            "Data4": "2012-04-29 01:41:42",
            "Data5": "0000-00-00 00:00:00"
        }
    ]
}
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Ray PaseurCommented:
I think you might want to change this:

 while($row = $result->fetch_assoc()) {

into this:

 while($row = $result->fetch_object()) {

With the new fetch method, you will get an array of objects in $jsonObj.  Then you can create a new object instance of StdClass and add the success property and the test_table property.  Send that new object to json_encode().
0
Puneet AroraFounderAuthor Commented:
Okay Ray , I will now try it out !
0
Slick812Commented:
greetings Puneet Arora, , I read this part of your comments -
   "Need a output which show success flag with index of all the values from test table"

and this -
"I need output  as an array and object both .. I either get it as array or object , "

But I fail to understand what you may mean when you give this as an example -
an out put like : {
    "success": 1,
    "test_table": [
        {
            "id": "1",
            "Data1": "SomeData",
            "Data2": "Some Data 300.00",
            "Data3": "Some Data XX",
            "Data4": "2012-04-29 01:41:42",
            "Data5": "0000-00-00 00:00:00"
        }
    ]
} 

Open in new window


I will guess that you need the -
    "success": 1,
or
   "success": 0,

to tell your JSON receiver that the SELECT found or did not find and rows?, as to your other property the -
    "test_table": [ ]
array. You seem to need that as an array of name-value pairs collections.

just as a "Guess", maybe code like -
       $jsonObj =  array('success' => 0, 'test_table' => array());
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $newArray =  array();
      foreach ($row as $key => $value) {
      $newArray[$key]  = $value;
       }
$jsonObj['test_table'] [] = $newArray;
    }
} else {
    $jsonObj['success'] = 0;
}

header('Content-type: application/json');
$out = json_encode($jsonObj);
echo  $out;

Open in new window

This may have some errors, because I can not test it now, but it may give you some ideas to use.
0
Ray PaseurCommented:
I think you may want to use the fetch_object() method instead of fetch_assoc().  JavaScript does not have associative arrays, so if you want named keys you must use an object.  I'm unsure as to whether PHP json_encode() is smart enough to take an associative array and turn it into an object automatically, so rather than guess, I would just get the results set as an array of objects.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Slick812Commented:
@ Ray , you do not need any PHP objects at all, for the  json_encode( ) , you might look at the manual here -
     http://php.net/manual/en/function.json-encode.php

the very first code example uses an assosiative array -
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);

Open in new window

which will output a javascript Object in text string notation -
     {"a":1,"b":2,"c":3,"d":4,"e":5}

 what most do not realize for the json_encode( ) result, is that the string representation is using a string operation as a much used "comma separated values" string container, with the second level in the JSON notation for an object in { }, the key-value delimiter is a colon  :  instead of a comma ,

I have many many times successfully used multilevel associative arrays in the  json_encode( ) function, with very correct JSON string output on all the different servers that it was used.
Thats why I gave that code example. which now that I look at it I can see it could be shortened in code work with just an equal sign =
       $jsonObj =  array('success' => 0, 'test_table' => array());
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
// I just set the new test_table array element equal to the row array
    $jsonObj['test_table'] [] = $row;
    }
} else {
    $jsonObj['success'] = 0;
}

header('Content-type: application/json');
echo json_encode($jsonObj);

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.