首页 > 解决方案 > 问题获取函数结果以回显

问题描述

我刚开始学习更多关于函数的知识,目前还停留在其中的一部分上。我正在尝试获取我在返回中设置的函数的结果,以在特定位置填充 html。

有谁看到我做错了什么?

这是错误消息:

PHP 致命错误:未捕获的 ArgumentCountError:函数 profilePic() 的参数太少,第 76 行的 /adminNav.php 中传递了 0,而 /adminNav.php:6 中预期的正是 1 堆栈跟踪:

0 /adminNav.php(76): profilePic()

1 /admin/project-gallery.php(93): 包括('pub...')

2 {main} 在第 6 行的 /adminNav.php 中抛出

完整代码:

function profilePic($con) {
    try {
        //Profile pic in main
        $sqlProfileImg = "
            SELECT *
            FROM profile_img
            WHERE user_id = ?
            ORDER BY id DESC
            LIMIT 1
            ";
        if ($stmtProfileImg = $con->prepare($sqlProfileImg)) {
            $stmtProfileImg->execute(array($user_id));
            
            $default_profile_img = NULL;
            $userProfilePic = NULL;
            $profilePic = NULL;
            $profilePicRows = $stmtProfileImg->fetchAll(PDO::FETCH_ASSOC);
            foreach ($profilePicRows as $profilePicRow) {
                $profilePic = $profilePicRow['img'];
                $profilePic = (!empty($profilePic) && $profilePic != 0)? $profilePic : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profilePic) && $profilePic != 0)? "Profile Picture" : "No Picture";
            }
        }
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
        $date = new DateTime();
        file_put_contents('error_log_profile_pic', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
        return false;
    }
    return $profilePic;
}

HTML

<img id="navUserProfilePic" src="<?php profilePic(); ?>">

标签: phpfunctionecho

解决方案


您需要将参数传递给该函数

例如,像这样

<img id="navUserProfilePic" src="<?php echo profilePic($con); ?>">
                                       ^^^^            ^^^^

您的另一个问题是范围。该函数对名为的变量一无所知$user_id


推荐阅读