0

I'm trying to simply echo a JSON object literal which includes every row in my database table.

As standard with the methods found in many other similar questions I looked at, I'm fetching every row and encoding it like so:

$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");

$rows = array();

while($r = mysqli_fetch_array($result))
  {
       $rows[] = $r
       //or: $rows[] = array('data' => $r);
  }

echo json_encode($rows);

Similarly to the question PHP: can't encode json with multiple rows or mysql table to json ,

I want to echo a JSON Object which looks like this:

    {
    "data1":   // how do I get "data1"?
        {
            name: John Smith,
            title: Mr,
            description: a man
        }
    }

    {
    "data2":{ // how do I get "data2"? 
            name:Bob Smith,
            title: Mr,
            description: another guy
        }

    }

Except I do not get how to achieve the "headers", the titles of the first level string of objects, such as "data1" or data2". In fact, my database table doesn't necessarily even have those values/that column.

This is what it looks like right now: database table

How can I get simply numerical "headers" like "1", "2" or "data1", "data2" without having to designate the "name" column as the "headers"? (Or do I have to have a column for that?)

My goal is to process the values in every "row" in the returned JSON.

I plan to use the jQ $.each function $.each(data, function(dataNum, dataInfo) -- e.g. data1 would be passed to dataNum and the values would be passed to dataInfo -- and be able to access specific table values by dataInfo.name, which right now is not working.

Thanks to any help in advance!

Community
  • 1
  • 1
LazerSharks
  • 3,089
  • 4
  • 42
  • 67

2 Answers2

2

I would think you are way better off using mysqli_fetch_object() to get each row as it own object. When you then json_encode $rows you would have an array of objects.

Here is the code:

$con=mysqli_connect("localhost","username","pass","markers");//markers is db table name
$result = mysqli_query($con,"SELECT * FROM markers");

$rows = array();

while($r = mysqli_fetch_object($result))
  {
       $rows[] = $r;
  }

echo json_encode($rows);

Your JSON would look like this:

[
    {
        "name":"Some Name",
        "title":"Some Title",
        "description":"Some description"
    },
    {
        "name":"Some Other Name",
        "title":"Some Other Title",
        "description":"Some other description"
    },
    ...
]

In javascript, that gives you an integer-indexed array of objects. So your javascript might look like this:

var array = JSON.parse(jsonString);
$.each(array, function(key, value) {
    alert(key); // numerical index
    alert(value.name); // name
    alert(value.title); // title
    alert(value.description); // description
});
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • 1
    @Gnuey Just to show that the JSON passed from PHP needs to be parsed into an array by javascript. Depending on how you are working with javascript (like using certain jQuery `ajax()`, `post()` options or using `getJSON()`) this step might be done automatically for you. If you are simply outputting this on page load into a javascript block, you can also skip this step by just outputting as a literal array (i.e. `var array = ;`) – Mike Brant Mar 26 '13 at 00:23
  • Ah, yep, I am using .getJSON. Thank you for your clear and thorough answer! I will try this method and get back to this – LazerSharks Mar 26 '13 at 00:29
  • I've tried to access the JSON with .each and using parameters equivalent to key and value to access the values, but nothing is displaying when I try to output it to HTML. If I were to not use ".each", how could I access a specific instance's name/title/description (just to test my JSON)? This was part of my original problem, as I thought I should have "headers" like 1,2,3,4 so I could simply iterate through each literal instance. – LazerSharks Mar 26 '13 at 19:17
  • @Gnuey Is you getJSON actually working? Can you verify (via console.log, alert, etc.) that you are getting the data de-serialized that way you are expecting? – Mike Brant Mar 26 '13 at 20:37
  • For some reason, my alert() function does not even output an alert box inside my getJSON function, ex: `$.getJSON('school2.php', datavar, function(data) { alert('hello'); });` An alert box with 'hello' will not even show up. But outside this function it will. :( – LazerSharks Mar 26 '13 at 23:41
  • @Gnuey It sounds like you are not getting a successful HTTP response. You should look at the HTTP request/response information for the AJAX request to see if you can see what the problem is. – Mike Brant Mar 27 '13 at 00:08
  • Ah, I finally got alert() and console.log() to work and outputting the right object literals with the .each() function! Thank you. fetch_object did the trick, though I am curious as to the difference between fetch_array and fetch_object, as I tried fetch_array and it seemed to work as well. I ended up creating a new .php file, designated to the .getJSON function, which would process and echo nothing else except that JSON object, whereas the previous .php file was echoing other things prior to the json_encode. – LazerSharks Mar 27 '13 at 08:03
  • 1
    @Gnuey Fetch object will return the result set record with all fields as properties. Fetch array, will return both an array with BOTH numerical indexing and associative indexing. For this case you would want fetch_object or fetch_assoc (which returns only the associative array). Now when PHP encodes JSON, associative arrays are encoded as objects anyways (since JSON format has no concept of associative arrays), so either would work equally from javasciptt standpoint. I however prefer to be explicit about what I am serializing and not have some behind the scenes conversion. – Mike Brant Mar 27 '13 at 16:00
0

Create indexes in your $rows variable:

<?php

$t['a'] = array ('name' => 'foo');
$t['b'] = array ('name' => 'bar');

echo json_encode ($t);
?>

In your case, a simple integer should do the trick, or something like $rows['data' . $i] followed by a $i++.

JvO
  • 3,036
  • 2
  • 17
  • 32
  • Don't tiptoe around numeric indices. Why is `$rows['data' . $i]` any better than a proper integer-indexed array? – Matt Ball Mar 26 '13 at 00:10
  • Because he asks for it? :-P – JvO Mar 26 '13 at 00:12
  • Well, I don't necessarily need the "data1". I just want some way to access values by `data.name` or somehow in my jQuery. – LazerSharks Mar 26 '13 at 00:16
  • So right now I'm trying `$rows['data' . $i] = $r; $i++` and accessing members by `data.data1.name`. However it's not displaying. Is there a way I can check my echoed json object? – LazerSharks Mar 26 '13 at 00:26
  • Yes, use your browser. If it is an Ajax callback, use Firebug or similar too to view the returned data (use the Network or Resources tab); if it is part of your generate page, simply view the source code. AFAIK there is no function to dump the contents of an JSON object (but who knows...) – JvO Mar 26 '13 at 00:32