【发布时间】:2018-06-28 18:25:27
【问题描述】:
我有一个textarea 来创建一篇文章,然后将其加载到数据库中。
我还具有按章节编号获取文章以在网站上显示的功能。
该函数运行良好,但获取的数据,或者更好地说,来自 PHP 函数的所有回声都直接进入了 body-tag,这会破坏我的布局。
我想知道,如何将 PHP 输出中的数据显示到我的 HTML 中的特定区域?
index.html:
<body>
<div class="main">
<h1>WebDev's Playground</h1>
<p>Momentaner Versuch: Formatierte Texte in Datenbanken speichern.</p>
<div class="playground">
<form action="?send=1" method="post">
<label for="heading">Überschrift</label>
<input name="heading" type="text" style="display:block;" />
<label for="chapter">Kapitel</label>
<input name="chapter" type="number" style="display:block;"/>
<textarea name="textbereich" rows="10" cols="130"></textarea>
<input type="submit" style="display:block;" />
</form>
</div>
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
</div>
</div>
</body>
这是来自我的 logic.php:
//BEGINNING fetching data / ouput data
if (isset($_GET['read'])) {
$id = "";
$chapter = $_POST['chapter'];
$heading = "";
$textbereich = "";
$error = false;
$errormessage = "Es ist folgender Fehler aufgetreten: ";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
print ("<h2>" . $ergebnis['heading'] . "</h2>");
print ("<p>Kapitel: " . $ergebnis['chapter'] . "</p>");
print ("<pre>" . $ergebnis['content'] . "</pre>");
}
}
//END fetching data/ output data
?>
解决方案:我必须将数据存储在变量中,并在所需区域的 HTML 中调用它们。
$outputHeading = "";
$outputChapter = "";
$outputContent = "";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
$outputHeading = $ergebnis['heading'];
$outputChapter = $ergebnis['chapter'];
$outputArticle = $ergebnis['content'];
}
在 HTML 中:
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
<h2><?php echo $outputHeading;?></h2>
<h2><?php echo $outputChapter; ?></h2>
<pre><?php echo $outputContent; ?></pre>
</div>
【问题讨论】:
-
用 环绕你的 php 代码
-
这两个陈述不矛盾吗: if (isset($_GET['send'])) { $chapter = $_POST['chapter']; // 您正在检查一个 get 变量,然后是一个 POST 变量?
-
你想在 if (isset($_GET['read'])) { ? - 然后不要打印,将它收集在一个变量中,例如 $lsOutput = "
... 并在你想要的地方回显它。echo $lsOutput;
-
@Dwza 我会马上查的。最好从头开始以正确的方式学习它,而不是在经过数月的“错误”练习后重新思考。
-
@Dwza HTML 和 PHP 存储在不同的文件中。我现在更改了
action="?send=1"并将其替换为隐藏输入<input name="send" type="hidden" value="true" />。在我的 PHP 文件中,我将if(isset($_GET['send')更改为if(isset($_POST['send'])。它工作正常。我将研究 smarty,可能会在接下来的几天内进行一些测试。