如何解决变量在 PHP 模板中变成未定义的变量
目前,我在将输出值返回到 PHP 模板时遇到问题,因为我收到一条错误消息,指出该变量在实际定义时未定义。我有一个 index.html.php 模板,其中包含所有 HTML,并且应该在主要部分打印 $output 变量值。
<main>
<div class="container">
<?=$output?>
</div>
</main>
与此同时,在我的 index.php 文件中,$output 设置为 products.html.php 文件的 ob_get_clean()(请参阅下面);
<?php
try {
//Connect to the database
$pdo = new PDO ('mysql:host=localhost;dbname=scandiweb;charset=utf8','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * FROM `products`';
$products = $pdo->query($sql);
$title = 'Product list';
//Starts output buffer.
ob_start();
include __DIR__ . '/../templates/products.html.php';
//Stores contents of output buffer into a variable
$output = ob_get_clean();
} catch (PDOException $e) {
$title = 'An error has occurred';
$error = 'Database error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();
}
include __DIR__ . '/../templates/index.html.php';
在 products.html.php 中,我循环遍历 SQL 返回的数据,这些数据应该存储在 $output 变量中:
<?php foreach ($products as $product): ?>
<div class="card my-2">
<div class="card-body">
<p class="card-text text-center"><?php echo htmlspecialchars($product['sku'],ENT_QUOTES,'UTF-8') ?></p>
<p class="card-text text-center"><?php echo htmlspecialchars($product['name'],'UTF-8') ?></p>
<p class="card-text text-center"><?php echo htmlspecialchars($product['price'],'UTF-8') . '$'?></p>
<?php if (!is_null($product['size'])): ?>
<p class="card-text text-center"><?php echo 'Size: ' . htmlspecialchars($product['size'],'UTF-8') . ' MB'?></p>
<?php endif; ?>
<?php if (!is_null($product['dimensions'])): ?>
<p class="card-text text-center"><?php echo 'Dimensions: ' . htmlspecialchars($product['dimensions'],'UTF-8')?></p>
<?php endif; ?>
<?php if (!is_null($product['weight'])): ?>
<p class="card-text text-center"><?php echo 'Weight: ' . htmlspecialchars($product['weight'],'UTF-8') . ' KG'?></p>
<?php endif; ?>
<form action="deleteproducts.php" method="post" class="text-center" id="deleteForm">
<input type="checkbox" name="checkbox[]" class="text-center" value="<?=$product['sku']?>">
</form>
</div>
</div>
<?php endforeach; ?>
但是,最后,当我测试 index.php 页面时,我收到错误消息,指出 $output 变量未定义,而它应该返回foreach 循环的结果。我使用相同的结构构建了另一个项目,一切正常,但是,在这里找不到变量未定义的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。