1

I guess I have a really simple question. I have a simple HTML page which I want to fill up with words from a mysql database.

Therefore I wrote this little test page. My problem is, that the first echo "Picture" works fine but the second one "Name" won't output anything. It works only the first time. If I add this:

$sql = <<<SQL
    SELECT *
    FROM `Database1`
    WHERE `id` = 1 
SQL;

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){

before the second echo "Name" everything works fine.

<?php
$db = new mysqli('', '', '', '');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$sql = <<<SQL
    SELECT *
    FROM `Database1`
    WHERE `id` = 1 
SQL;

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}
?>

<html>

<img src="<?php
while($row = $result->fetch_assoc()){
    echo $row['Picture'];}
?>" height="270">

some more html...

<?php
    echo $row['Name'] . '<br />';
?>                          

even more html...

<?php
    mysqli_close ($con);
?>  

</html>

Is this the way to go? Or did I miss something?

Thank you!

1
  • 2
    If you will notice here echo $row['Picture'];} you have ended the while loop of php. So whatever comes after it, will not show. Commented Jun 10, 2018 at 13:11

1 Answer 1

2

Found the solutions by myself: The trick is to move the pointer to row 0 again after the while loop:

mysqli_data_seek($result, 0);

Docs

Sign up to request clarification or add additional context in comments.

1 Comment

you can also save all records to an array variable (with fetch_all) and then cycle on the array and not on the results.

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.