这个很简单,但今天我已经进入了这么多圈子,我完全迷失了!
我正在尝试根据我在页面顶部设置的变量来获取正确的页面标题和页面内容。即:
<?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>
我知道我在这里犯了一个非常愚蠢的错误......只是不确定在哪里。
答案 0 :(得分:2)
您有三个大错误:
您忘了将$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);
Stack Overflow:
$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。
答案 1 :(得分:1)
你第一个错误就是忘记了MYSQL_ * 。使用PDO 其次,你说你想抓住$ pageIDn = 2,但你根本就没用过。
function content($pageID){
$query = mysql_query("SELECT * FROM pages WHERE id = ".$pageIDn." ");
$row = mysql_fetch_array($query);
$title = $query['title'];
$content = $query['content'];
}