waldbaum waldbaum -4 years ago 110
PHP Question

PHP variable declared global doesn't work within function

I am using a HTTP query string to pass an id. The variable I assign it to works perfectly for the queries immediately following. However, it doesn't work within any of the functions which I define in the same file, although I declared the variable as global.

$circleID = $_GET['id'];


$circleID
works well for this query:

// 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'];


It doesn't work within the following function though.
$circleID
seems to be empty in this context:

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);
}
}


Apologies if this is a trivial question. I am new to php and spent a considerable amount of time trying to solve this, but I'm stuck.

Answer Source

See why this will not work

Suppose that you have sent an get request to a page

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

Now you are making once again the post request to this page

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

Now since you want to access the previous get data in the post data you have to save the get data in the session since on the next request all the data from the previous request will be lost

so in starting of the page

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

and in the remove function

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);
}

}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download