0
<?php
    require_once 'init.php';

    $selectpost = mysql_query("
        SELECT 
         posts.id, 
         posts.author, 
         posts.postText

        FROM posts

        GROUP BY posts.id

   ");
    while($row = mysqli_fetch_object($selectpost)) { //line 30

        $posts[] = $row;    
    }
?>

<?php foreach($posts as $post): ?> //line 37

    <div class="post row">
     <p><?php echo $post->author; ?> said: </p>
     <p><?php echo $post->postText; ?></p>
    </div>

<?php endforeach; ?>

I am trying to display some posts from a database. This is my code I have written so far. For some reason I am getting these errors:

Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in posts.php on line 30

Notice: Undefined variable: posts in posts.php on line 37

Warning: Invalid argument supplied for foreach() in posts.php on line 37

I have commented on the appropriate lines.

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

0

You are mixing mysql & mysqli.It should be mysqli_query instead of mysql_query if you are using mysqli. You are missing the connection object -

$selectpost = mysqli_query($conn, "
        SELECT 
         posts.id, 
         posts.author, 
         posts.postText
        FROM posts
        GROUP BY posts.id
   ");

mysqli

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • $conn = new mysqli("host","root","pass","mydb"); is it fine to connect just like this in mysqli? –  May 08 '15 at 06:09
0

I changed and tested working fine, check once. In your code not connects db so records not comming..

 <?php
    //require_once 'init.php';
    $con=mysql_connect("localhost","root","");
    $db=mysql_select_db("test",$con);
    $selectpost = mysql_query("
    SELECT 
     posts.id, 
     posts.author, 
     posts.postText
     FROM posts
     GROUP BY posts.id
     ");
     while($row = mysql_fetch_object($selectpost)) { //line 30
     $posts[] = $row;    
    }
 ?>

<?php print_r($row);  foreach($posts as $post): ?> 

<div class="post row">
 <p><?php echo $post->author; ?>  </p>
 <p><?php echo $post->postText; ?></p>
</div>
Raju
  • 185
  • 1
  • 11