How to access PHP variable from while(mysql_fetch_array($query)) function call in the next <?php?>
tag for separate HTML?
<body>
<?php
$sql="select * from $table order by id desc";
$query=mysql_query($sql) or die(mysql_error());
while($result=mysql_fetch_array($query)){
$id=$result[id];
$subject=$result[subject];
$subjectpic=$result[subjectpic];
$content=$result[content];
//global $id, $subject, $subjectpic, $content; ?
}
?>
<div class="subject">
<?php
print"$subject";
?>
</div>
<div class="subjectpic">
<?php
print"$subjectpic";
?>
</div>
</body>
Thanks a lot!
Actually you can simply put the closing brace further down...
<body>
<?php
$sql="select * from $table order by id desc";
$query=mysql_query($sql) or die(mysql_error());
while($result=mysql_fetch_array($query)){
$id=$result['id'];
$content=$result['content'];
?>
<div class="subject"><?php print $result['subject']; ?></div>
<div class="subjectpic"><?php print $result['subjectpic']; ?></div>
<?php } ?>
</body>
This version is more readable, though:
<body>
<?php
$sql="select * from $table order by id desc";
$query=mysql_query($sql) or die(mysql_error());
while($result=mysql_fetch_array($query)){
$id=$result['id'];
$content=$result['content'];
sprintf('<div class="subject">%s</div>'."
", $result['subject']);
sprintf('<div class="subjectpic">%s</div>'."
", $result['subjectpic']);
}
?>
</body>
$subject
and the other variables print the values of the last row only. If you are planning to iterate over the values of the variables as you loop through the array consider printing/echoing them within the while
block itself.
just move the curly brace down
//global $id, $subject, $subjectpic, $content; ?
?>
<div class="subject">
<?php
print"$subject";
?>
</div>
<div class="subjectpic">
<?php
print"$subjectpic";
?>
</div>
<?php
}
?>
</body>