php - 不会在另一个脚本中读取函数中的变量

标签 php mysql

每当我将输入字段留空时,应该设置并回显 $error['commment'],但它不会回显,但如果我只是说 echo "some text ";,回显就是了。 comments 函数在我的 functions.php 文件中,$error[] = array() 在我的 comments() 函数上方的 text.php 文件中给出,所以我不明白为什么它不起作用,请帮助大家。

最后一段 PHP 代码在一个 while 循环中,它必须显示我的 SQL 查询的所有结果。

text.php 中我的 HTML 上方的代码:

<?php

session_start();

include("connect.php");
include("functions.php");

$userId = "";

if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
    $userId = $_SESSION['id'];
}


$error[] = array();

comments();
?>

我的 functions.php 中的代码:

function comments(){
if (isset($_POST['submit'])) {
    $text = $_POST['text'];
    $filledIn = true;

    if (empty($text)) {
        $error['comment'] = "No text filled in";
        $filledIn = false;
    }

}

}

这是我的 text.php 中的代码:

<?php
if(isset($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>

最佳答案

因为$error不在comments()函数的范围内。所以 $error['comment'] 永远不会被设置。

理想情况下你会想做这样的事情:

文本.php

session_start();

include("connect.php");
include("functions.php");

$userId = "";

if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']){
    $userId = $_SESSION['id'];
}

$error['comment'] = comments();

函数.php

function comments(){
    if (isset($_POST['submit'])) {
        $text = $_POST['text'];    
        if (empty($text)) {
            return "No text filled in";
        }
    }
    return null;
}

文本.php

<?php
if(!empty($error['comment'])) echo "<p class='error'>".$error['comment']."</p>";
?>

我不会直接设置数组键“comments”,而是使用 comments() 函数的返回值来设置它。这使您可以避免使用全局变量。

编辑:我从 comments() 中删除了 $filledIn 变量,因为它没有在提供的代码中使用。

关于php - 不会在另一个脚本中读取函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809344/

相关文章:

mysql - DBIC 加入 Catalyst Web 应用程序

mysql - 如何自定义插入数据?

mysql - MySQL 中对多列进行操作的函数

javascript - 删除函数后返回首页 PHP MYSQL JAVASCRIPT

php - 在 php 中选择 auto_increment 字段返回空白

我为测试制作的简单表格的 PHP/MySQL 错误(我正在尝试自学一些 MySQL/PHP)

php - if (isset($_GET ['editpersonnel' ])) 不起作用

php - 在 php 中将年添加到今天的日期

php - 在 php 中选择查询 mysql 后运行更新或插入查询

mysql - 添加语句 WHEN CASE SQL