Reputation: 6549
EDIT Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D
Thanks to all!
Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:
Main page:
<?php include 'includes/header.php'; ?>
<?php getPosts();?>
<div>Some HTML Code</div>
<?php endPosts(); ?>
Header.php
function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};
Any idea why this won't work? I'm getting a blank white screen right now.
Upvotes: 0
Views: 90
Reputation: 60013
That's not really how PHP works. After including the header file, PHP will see something like this:
<?php
function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*This is just an empty function */
}; /*And here is where getPosts ends*/
?>
You seem to be confused between what includes and function calls achieve.
What I think you want to be doing is something like:
<?php
getPosts();
while($row = mysql_fetch_array($result)) {
?><div>Some HTML Code</div><?php
}
?>
Upvotes: 0
Reputation: 116160
You're essentially trying to create a parameterless function named endPosts
for each row in posts. I don't even know what you're trying but this won't work. You can't declare a function twice.
And even if you could, endPosts
doesn't do anything, so even if this would be valid code, it wouldn't output anything (except for the div).
Upvotes: 0
Reputation: 2856
I think you are missing the core understanding of what a function is. Variables inside one function cannot be accessed by another function unless passed into the function.
Also you can not start a procedural statement (while loop) in one function and end it within another function.
Upvotes: 1
Reputation: 760
I don't think that kind of stripping in functions will work. Aren't you getting errors from the PHP parser?
You should use something like this:
<?php $res = getPosts() ?>
<?php while ($item = mysql_fetch_array($res)): ?>
<div>Some HTML code</div>
<?php endwhile; ?>
With your getPosts()
function like:
function getPosts()
{
$query = mysql_query("SELECT * FROM posts order by id desc");
if (!$query) die('MySQL error');
return $query;
}
Upvotes: 1
Reputation: 10091
That code is so not valid. Why are you declaring a function inside of another function? And there aren't supposed to be semicolons on the end of function declarations/loops. The first thing to do is to enable error reporting.
Upvotes: 1