【问题标题】:PHP: Global keyword not working after POST requestPHP:POST请求后全局关键字不起作用
【发布时间】:2021-07-18 04:23:31
【问题描述】:

我有一个供用户编辑个人详细信息的 PHP 表单。出于某种原因,我需要知道哪个值已被用户修改,而不是将所有详细信息都覆盖到数据库中。页面加载后,将首先执行 else 语句 以从数据库中获取内容并将其显示在页面上。一旦点击了表单的提交按钮,就会执行if语句。

<?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>

我打算比较 if 语句 中的$everywhere 和$edited,以便了解修改了哪个值。但是$everywhere 在 if 语句 中已变为未定义。有办法解决这个问题吗?

【问题讨论】:

    标签: php forms post mysqli global-variables


    【解决方案1】:

    if 语句中有一个$everywhere 的拼写错误,else 语句中有一个拼写错误。

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

    【讨论】:

    • 感谢您的提醒。我已经更新了这个问题。但是如果没有拼写错误,它仍然无法工作。
    • 你试过没有global $everywhere; 行吗?仅当变量位于用户定义的函数中时,才需要 global 关键字。在 PHP 中,如果只是在 if 语句代码块中,则不需要它。 If 代码块与您定义 $everything 的代码块之外的范围相同。
    • 我试过了。它不起作用。我知道如果我在 if 语句 中再次从数据库中获取内容,问题就可以解决,但我想知道是否有更聪明的方法来解决它。这样用户就不必一直向服务器发送请求
    • 一旦用户点击提交,$everywhere 将不包含$everywhere = $items; 行给它的数据。一种解决方案是您可以创建包含原始数据库内容的隐藏输入字段,然后将其作为表单数据传递,并且可以在 PHP 中进行检查。
    • 我用另一种方式解决了这个问题,但我同意你提到的解决方案也是可行的。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多