bobbyjones
bobbyjones

Reputation: 2079

calling a variable in PHP while loop

i have a website structure as follow

<div id="title">
<h1> //call $title here after executing loop </h1>
</div>
<?php 
   ...
     while ($row = $result->fetch_assoc()) { $title = $row['title']; ?>

<h2> this is the <?php echo $title;?> </h2>
<?php } ?>

is there a way i could still use or call the $title variable on an html element on top of the while loop statement?

whenever i call it above the while loop i get errors like Undefined variable: id..

edit: change id into 'title' instead

Upvotes: 0

Views: 112

Answers (2)

Elon Than
Elon Than

Reputation: 9765

PHP will read code line by line so variable can't be used before declaration.

Only one option is to move loop above your div, get html from loop inside variable and print it later.

I think that you've got only one row in that loop so use this code instead.

$row = $result->fetch_assoc();
$title = $row['title'];
echo '<h2> this is the '.$title.' </h2>';

Upvotes: 2

George Brighton
George Brighton

Reputation: 5151

If you're only retrieving a single row, you don't need the loop:

<?php
$row = $result->fetch_assoc();
$title = $row['title'];
?>

<div id="title">
    <h1><?php echo $title; ?></h1>
</div>

Upvotes: 0

Related Questions