Search code examples
phpformspostmysqliglobal-variables

PHP: Global keyword not working after POST request


I've an PHP form for users to edit personal details. For certain reason, I will need to know which value has been modified by the users instead of overwriting all details to the database. Once the page is loaded, the else statement will first be executed to fetch content from database and display it on the page. Once the submit button of the form is clicked, the if statement will be executed.

<?php
$everywhere = [];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //once the submit button is clicked, collect all the values from the form
    $edited = [];
    $edited['Name']= ...;
    $edited['Address'] = ...;


    //error 
    //$everywhere becomes undefined 
    global $everywhere;
    foreach($everywhere as $x=>$x_val){
        echo "<h2>".$x."=".$x_val." "."</h2>";
    }
    
    
}else{ 
    //sqli_ query line
    //sqli_fetch_assoc line
    
    //original personal details will be stored into $items
    $items = [];
    $items['Name'] = ...;
    $items['Address'] = ...;
    
    global $everywhere;
    $everywhere = $items;
}

?>

<!--display original personal details-->
<form method="post">
    <dl>
        <dt>Name</dt>
        <dd><input type="text" name="user_name" value="<?php echo $items['user_name']; ?>"/></dd>
    </dl>
    ......
    ......

    <input type="submit" value="Edit"/>
</form>

I plan to compare the $everywhere and $edited in the if statement so that I get to know which value has been modified. But $everywhere has become undefined in the if statement. Any idea to solve this problem?


Solution

  • There is a spelling mistake of $everywhere in the if statement, and another in the else statement.

    ...
        global $everywhere;
        foreach(**$everywhere** as $x=>$x_val){
            echo "<h2>".$x."=".$x_val." "."</h2>";
        }
    ...
        global **$everywhere**;
        $everywhere = $items;
    }
    
    ?>
    ...