简体   繁体   English

如何将该Postgres数据库查询的结果转换为json以返回到我的jquery调用?

[英]How can I convert the result of this postgres db query into json to return to my jquery call?

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. 单击并在下拉列表中选择一个项目时,它需要某种类似于AJAX的行为。

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. 我知道我需要做一个jquery ajax调用。 So I think my onStudentChange() function would look like this: 所以我认为我的onStudentChange()函数看起来像这样:

$.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. 因此,我继续创建了get_registered_events.php ,我想返回学生注册的事件。

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. 我的问题是,我对PHP没有经验,并且在弄清楚如何返回数据库给我的JSON格式的ajax调用数据时遇到困难。 Another snag I have is our school is using a very old version of PHP so I have to use this PEAR JSON library. 我遇到的另一个障碍是我们学校正在使用非常旧的PHP版本,因此我必须使用此PEAR JSON库。

Here is that PHP file I'm having trouble with: 这是我遇到麻烦的PHP文件:

<?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. 所以我的问题是,我如何将$ contests(其行)转换为JSON(contest.id,commit.title),然后将其返回给进行上述操作的ajax调用。

If anyone could point me in the right direction I would really appreciate it. 如果有人能指出正确的方向,我将不胜感激。

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 这会将每一行编码为JSON对象,并以列名作为键,并将所有行放入JSON数组中

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() 如果您担心数据的大小,请使用@ atif089,但请使用pg_fetch_assoc()而不是pg_fetch_row()

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

echo json_encode($myarray);

I think this have to work. 我认为这必须起作用。

From postgresql 9.3 you can get result directly as a json array with json_agg: 从PostgreSQL 9.3开始,您可以使用json_agg作为json数组直接获取结果:

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 http://www.postgresql.org/docs/9.3/static/functions-aggregate.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM