为什么这个查询失败了?

时间:2013-01-28 15:50:07

标签: php jquery psql

<?php

$connect = pg_connect("dbname=$dbase host=".$host." user=".$user." password=".$pass) or die("I sense a disturbance in the force ");

$action = $_POST['action'];

switch($action){
case 'bagSubmit' : bagSubmit(); break;
}

function bagSubmit(){
    $sql = 'SELECT * FROM cntrt';
    $query = pg_query($connect,$sql) or die('could not connect');
}
?>

上面的php返回“无法连接”。 sql查询在数据库中执行正常。这是我在php中执行查询的常规过程(以前一直工作)。现在唯一的区别是我从jquery调用php。 jquery也正常运行,因为返回了查询失败('无法连接')这一事实。我错过了什么?

$.ajax({
    url: 'functions.php',
data: {action: 'bagSubmit'},
type: 'post',
success: function(response){
    $('body').append(response);
}
});

3 个答案:

答案 0 :(得分:7)

$ connect未定义。 你需要

function bagSubmit(){
    global $connect;
    $sql = 'SELECT * FROM cntrt';
    $query = pg_query($connect,$sql) or die('could not connect');
}

答案 1 :(得分:4)

<?php
    $host = "10.10.10.129";
    $user = "postgres";
    $pass = "";
    $dbase = "attest";
    $connect = pg_connect("dbname=$dbase host=".$host." user=".$user." password=".$pass) or die("I sense a disturbance in the force ");

    $action = $_POST['action'];

    switch($action){
        case 'bagSubmit' : 
            bagSubmit($connect); 
            break;
    }

    function bagSubmit($connect){
        $sql = 'SELECT * FROM cntrt';
        $query = pg_query($connect,$sql) or die('could not connect');
    }
?>

答案 2 :(得分:1)

不要使用全局变量,只需将$connect对象传递给函数:

function bagSubmit($connect){
    $sql = 'SELECT * FROM cntrt';
    $query = pg_query($connect,$sql) or die('could not connect');
}

并称之为:

bagSubmit($connect);