声明为全局的PHP变量在函数内不起作用

时间:2017-02-24 16:46:58

标签: php

我使用HTTP查询字符串来传递id。我赋予它的变量适用于紧随其后的查询。但是,它在我在同一个文件中定义的任何函数中都不起作用,尽管我将变量声明为全局变量。

$circleID = $_GET['id'];

$circleID适用于此查询:

// Retrieve circle data
$circleDataResult = mysqli_query($connection,"  SELECT     name, description
                                                FROM       circle
                                                WHERE      circleID = '$circleID' ");

$circleData = mysqli_fetch_array($circleDataResult);
$circleName = $circleData['name'];
$circleDesc = $circleData['description'];

但它在以下功能中不起作用。在这种情况下,$circleID似乎是空的:

if(isset($_POST['action']) && !empty($_POST['action'])) {
  $action = $_POST['action'];
  switch($action) {
      case 'removeUser' : removeUser(); break;
      case 'makeAdmin' : makeAdmin(); break;
      case 'revokeAdmin' : revokeAdmin(); break;
      case 'makeOwner' : makeOwner(); break;
  }
}

function removeUser(){
    global $connection;
    global $circleID;

    $thisUserID = $_POST['id'];

    $removeUserFromCircle = "   DELETE
                                FROM       circle_participants
                                WHERE      circleID = '$circleID' AND userID = '$thisUserID' ";

    if (mysqli_query($connection, $removeUserFromCircle)) {
        echo "You removed " . getName($thisUserID) . " from this circle";
    } else {
        echo "Error deleting record: " . mysqli_error($connection);
    }
}

如果这是一个微不足道的问题,请道歉。我是php的新手,花了相当多的时间试图解决这个问题,但我陷入困境。

2 个答案:

答案 0 :(得分:1)

为了总结其他遇到问题的答案:

似乎我希望通过GET从HTTP查询字符串值检索的id值被POST请求覆盖/设置为null,如user3411846所指出的那样。因此,当代码通过AJAX执行时,circleID被设置为null。 将会话变量与if(isset){}结合使用解决了这个问题!

这是我改变的代码:

if(isset($_GET['id'])){
    $_SESSION['circleid'] = $_GET['id'];
}

而不是:

$circleID = $_GET['id'];

在功能中:

function removeUser(){
    ...
    $circleID = $_SESSION['circleid'];
    ...
}

而不是:

function removeUser(){
    ...
    global $circleID;
    ...
}

答案 1 :(得分:0)

了解为什么这不起作用

假设您已向页面发送了获取请求

$a = $_GET['variable'];
echo $a ; // this will echo the variable
exit;

现在您再次向此页面发送帖子请求

$a=$_POST['variable'];
echo $a; // will print data if there exist data in the given variable
exit;

现在,由于您要访问发布数据中的先前获取数据,您必须在会话中保存获取数据,因为在下一个请求中,上一个请求中的所有数据都将丢失

所以在页面开始时

session_start()
$circleid = $_GET['id'];
$_SESSION['cirlceid'] = $circleid;

并在删除功能

function removeUser(){
global $connection;
$circleID = $_SESSION['circleid']

$thisUserID = $_POST['id'];

$removeUserFromCircle = "   DELETE
                            FROM       circle_participants
                            WHERE      circleID = '$circleID' AND userID = '$thisUserID' ";

if (mysqli_query($connection, $removeUserFromCircle)) {
    echo "You removed " . getName($thisUserID) . " from this circle";
} else {
    echo "Error deleting record: " . mysqli_error($connection);
}

}