Pablito Diaz
Pablito Diaz

Reputation: 5

function problems in PHP

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.

Upvotes: 0

Views: 62

Answers (4)

vicosoft
vicosoft

Reputation: 73

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.

Upvotes: 0

SamHuckaby
SamHuckaby

Reputation: 1162

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.

Upvotes: 0

Orangepill
Orangepill

Reputation: 24665

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>

Upvotes: 1

Marc B
Marc B

Reputation: 360872

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.

Upvotes: 1

Related Questions