0
<?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);
}
});
4

3 回答 3

7

$connect 未定义。你需要

function bagSubmit(){
    global $connect;
    $sql = 'SELECT * FROM cntrt';
    $query = pg_query($connect,$sql) or die('could not connect');
}
于 2013-01-28T15:52:10.550 回答
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');
    }
?>
于 2013-01-28T15:53:30.303 回答
1

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

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

并这样称呼它:

bagSubmit($connect);
于 2013-01-28T15:53:50.397 回答