将检索到的数据库记录传递到php文件

时间:2015-05-09 08:26:06

标签: php mysql include

系统/ article.php

<?php 

$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["articleTitle"];
        echo $row["articleSummary"];
        echo $row["articleContent"];
    }
} else {
    echo "0 results";
}

include 'template/homepage.php';

从文章表中检索文章。

我已经包含了homepage.php,它应该作为模板。

模板/ homepage.php

<?php include 'template/common/header.php'; ?>

  <h1>Article Title here</h1>
  <p>articleSummary</p>

<?php include 'template/common/footer.php'; ?>

我现在如何将检索到的数据传递给homepage.php以在浏览器上显示?

修改

smarber指着我

在第一个文件中:

global $variable;
$variable = "apple";
include('second.php');

在第二个文件中:

echo $variable;

哪个有效。但是如何在我的问题中实现同样的问题呢?

2 个答案:

答案 0 :(得分:1)

你可以通过GET,Session或Post do that;但是,为什么不简单有效地定义函数并将这些变量传递给它,例如:

function displayArticle($title, $summary, $content) {
    displayHeader(); // maybe some concepts you've used in template/common/header.php
    echo "<h1>$title</h1><p>$summary</p><div>$content</div>";
    displayFooter(); // again, what you've provided in footer.php
}

答案 1 :(得分:0)

那么,您可以执行以下操作:

template/homepage.php文件更改为:

<?php
include 'template/common/header.php';

echo "<h1>$articleName</h1>";
echo "<p>$articleSummary</p>";

include 'template/common/footer.php';
?>

并将system/article.php更改为:

<?php 
global $articleName;
global $articleSummary;
global $articleContents;

$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $articleName = $row["articleTitle"];
        $articleSummary = $row["articleSummary"];
        $articleContents = $row["articleContent"];

        include 'template/homepage.php';
    }
} else {
    echo "0 results";
}

但是,使用编程语言中的一些工具(如使用函数和类)创建更清晰,更可重用的代码会更好:)