0

I searched and searched and couldnt find any answer to my question So I'm sorry if this is a repost newbie here.

I have this function in a separate file called functions.php

function get_all_posts(){
global $connection;
$q = "SELECT * FROM blog LIMIT 1";
$get_posts = mysqli_query($connection, $q);
if (!$get_posts){
    die ('Query failed.');
}
return $get_posts;
}

And a called to function in blog.php

<div class="group">
        <?php get_all_posts();
            while ($row = mysqli_fetch_array($get_posts)){
         ?>
         <h1><?php echo $row['title']; ?></h1>
         <?php } ?>
        </form>
    </div>

But I keep having an undifined variable $get_posts.

0

4 Answers 4

1

You have to assign the results of get_all_posts to $get_posts;

<?php $get_posts = get_all_posts(); 
while ($row = mysqli_fetch_array($get_posts)){
     ?>
     <h1><?php echo $row['title']; ?></h1>
     <?php } ?>
    </form>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!, I've been all morning trying to figure this out!
1

You don't capture the returned value. e.g. you should have

$get_posts = get_all_posts();

If you don't assign the return value of a function to a variable, that return value is thrown away. So your query was basically useless.

Comments

0

Change the code in your blog.php to something like this:

<div class="group">
    <?php 
        $get_posts = get_all_posts();
        while ($row = mysqli_fetch_array($get_posts))
        {
     ?>
     <h1><?php echo $row['title']; ?></h1>
     <?php 
        }
     ?>
    </form>
</div>

Your function returns a value, but it doesn't pass it straight out. You have to capture it in a variable like so $newvariable = function(); and then you can use $newvariable wherever you want.

Comments

0

Sure! In order for you not to get undefined variable, you must assign value to your variable, in this scenario $get_posts, before using it in mysqli_fetch_array() function. The code Orangepill suggested will definitely work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.