这个很简单,但是我今天转了很多圈,我完全迷路了!
我正在尝试根据我在页面顶部设置的变量获取正确的页面标题和页面内容。即:
<?php
$pageIDn = 2;
include($_SERVER['DOCUMENT_ROOT'] .'/includes/functions.php');
content($pageIDn); // the function that queries the DB
include($_SERVER['DOCUMENT_ROOT'] .'/includes/header.php'); ?>
在函数中然后我有这个函数/查询:
function content($pageID){
$query = mysql_query("SELECT * FROM pages WHERE id = 1");
$title = $query['title'];
$content = $query['content'];
}
然后在文件的相关位置,我试图回显变量,即:
<h2><?php echo $content; ?></h2>
我知道我在某个地方犯了一个非常愚蠢的错误......只是不确定在哪里。
最佳答案
你有三个大错误:
您忘记将您的
$pageID
放入您的查询中:$query = mysql_query("SELECT * FROM pages WHERE id = {$pageID}");
...获取结果:
$row = mysql_fetch_assoc($query); $title = $row['title']; $content = $row['content'];
...并返回并捕获您的输出:
return array($title, $content); list($title, $content) = content($pageIDn);
堆栈溢出:
$pageIDn = 2;
include($_SERVER['DOCUMENT_ROOT'] .'/includes/functions.php');
list($title, $content) = content($pageIDn); // the function that queries the DB
include($_SERVER['DOCUMENT_ROOT'] .'/includes/header.php'); ?>
function content($pageID){
$query = mysql_query("SELECT * FROM pages WHERE id = {$pageID}");
$row = mysql_fetch_assoc($query);
$title = $row['title'];
$content = $row['content'];
return array($title, $content);
}
此外,Please, don't use mysql_*
functions in new code .它们不再维护 and are officially deprecated .查看red box ?了解 prepared statements相反,并使用 PDO , 或 MySQLi - this article将帮助您决定选择哪个。如果选择 PDO,here is a good tutorial .
关于php - 按 ID 查询数据库以获取页面标题和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187148/