Turlough
Turlough

Reputation: 15

trouble retrieving data from sql database with php

I'm pretty new to php, and I'm teaching myself. I've looked at a few different resources, and the php script I have now doesn't return any critical errors when executed, but its not returning the data from the table.

 <?php

$connect = mysqli_connect("localhost","*","*","*");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$comments = "SELECT * FROM commentstable";

$rs = mysqli_query($connect,$comments);

$fetch = mysqli_fetch_array($rs);

while($fetch = mysqli_fetch_array($rs)) {
    echo $fetch['comments'];

    }
echo $fetch;

mysqli_close($connect);

echo "hello";

?>

Upvotes: 1

Views: 61

Answers (2)

mmr
mmr

Reputation: 516

you have double entry:

$fetch = mysqli_fetch_array($rs); //<--- remove this as you are calling it again in the while loop

while($fetch = mysqli_fetch_array($rs)) {    
    echo $fetch['comments'];

}

Upvotes: 1

PKolos
PKolos

Reputation: 402

Check this

$connect = mysqli_connect("localhost","turlough","samus1","comments");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    $comments = "SELECT * FROM commentstable";

    $rs = mysqli_query($connect,$comments);
    if($rs)
    {
        while($fetch = mysqli_fetch_array($rs)) {
            echo $fetch['comments'];
        }
    }
    else
    {
        // no results from query
    }

    mysqli_close($connect);

}

Upvotes: 0

Related Questions