如何将此postgres db查询的结果转换为json以返回到我的jquery调用?

I'm creating a contest sign-up page for our annual math competition at my school. It requires some AJAX like behavior when you click and select an item in a dropdown list.

I've gotten an event to fire when I select something in the dropdown (I'm currently showing an alert box):

<script type="text/javascript">
    $(function() {
        $("#student").change(onStudentChange);
     });

     function onStudentChange()
     {
         alert("Dropdown changed");
     }
</script>

What this needs to do, is do an asynchronous call to the server to get a list of contests that student is currently registered for.

I know I need to do a jquery ajax call. So I think my onStudentChange() function would look like this:

$.ajax({
    type : 'POST',
    url : 'get_registered_events.php',
    dataType : 'json',
    data: {
    studentid : $('#student').val()
    },
    success : function(data){
        // Do something once we get the data
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
        // Display error
        }
        });

        return false;
});

So I went ahead and created the get_registered_events.php, which I want to return the events the student is registered for.

My problem is, I'm not experienced with PHP and I'm having difficulty figuring out how I would return the data the database gave me to this ajax call in the JSON format. Another snag I have is our school is using a very old version of PHP so I have to use this PEAR JSON library.

Here is that PHP file I'm having trouble with:

<?php

if (!empty($_POST['studentid')) {

    include_once('JSON.php');
    $json = new Services_JSON();

    $dbconn = pg_connect("host=somehost dbname=somedb user=someuser password=somepassword") or die('Could not connect: ' . pg_last_error());
    $query = 'SELECT contest.id, contest.title, FROM contest, student_contest WHERE student_id = '.$_POST['studentid'].' AND contest.id = contest_id';
    $contests = pg_query($query) or die('Query failed: ' . pg_last_error());

    // Here I need to convert the rows of $contests (contest.id, contest.title), into JSON and return it to that ajax call.

}

?>

So my question is, how do I convert $contests (its rows), into JSON (contest.id, contest.title), and return that back to the ajax call that will make it above.

If anyone could point me in the right direction I would really appreciate it.

$myarray = array()
while ($row = pg_fetch_row($contests)) {
  $myarray[] = $row;
}

echo json_encode($myarray);

I think this have to work.

You can also do

$resultArray = pg_fetch_all($result);
echo json_encode($resultArray);

This will encode each row as a JSON Object with the column name as the key and put all the rows in a JSON Array

Only do this if you know for sure that your query will return a small set of data. If you are worried about the size of data, use @atif089's but use pg_fetch_assoc() instead of pg_fetch_row()

From postgresql 9.3 you can get result directly as a json array with json_agg:

With p as (
SELECT contest.id, contest.title, FROM contest, student_contest WHERE student_id = '.$_POST['studentid'].' AND contest.id = contest_id
)
select json_agg(p) as json from p;

http://www.postgresql.org/docs/9.3/static/functions-aggregate.html