使用函数来简化 CMS 主题
我正在制作自己的 CMS。我有一些代码选择要在页面上回显的数据库行,如下所示:
$query = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
但是,每当我尝试将其放入函数并调用该函数而不是使用那么长的代码行时,什么也没有发生。我是否缺少 PHP 函数的某些内容?
function posts() {
mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error()); `
}
while($row = mysql_fetch_array(posts())) {
$id = $row['id'];
echo $id;
}
I'm in the process of making my own CMS. I have some code that selects database rows to be echoed out on the page like so:
$query = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
However whenever I try to put this inside a function and call the function instead of using that long lines of code, nothing happens. Am I missing something with PHP functions?
function posts() {
mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error()); `
}
while($row = mysql_fetch_array(posts())) {
$id = $row['id'];
echo $id;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要返回结果:
You need to return the result:
如果没有看到你的函数代码,就不可能说出问题是什么,但是如果我必须根据你的描述来猜测,我要检查的第一件事就是看看你是否(a)在你的函数中返回 $query 并且( b) 将返回值分配给调用代码中的其他内容。
更新:所以,根据您提出的代码,是的,问题是上面的(a)——您需要返回值。只需将“return”放在函数中一行代码的其余部分之前,它就应该可以工作。
Without seeing your function code, it's impossible to say what the problem is, but if I had to guess based on your description, the first thing I'd check is to see if you are (a) returning $query in your function and (b) assigning the return value to something else in your calling code.
UPDATE: So, based on the code you posetd, yes, the problem is (a) above--you need to return the value. Just put "return" before the rest of the one line of code in the function and it should work.