2

I want to grab data from a mysql database by using php. The data looks something like this:

apple 3
orange 2
banana 4

I want to take the data and put it in a html table and use css to make it look pretty, but I dont want to deal with it inside <?php ?>

After I grab the

$result = mysql_query("SELECT * FROM Table");

can I reference the result variable outside the <? php ?> tags?

5 Answers 5

1

No. PHP can only be done in <?php ... ?> or <?= ... ?>. Use a template engine such as Smarty if you want substitution in this manner.

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

3 Comments

so how would u put the data in a html table?
@SuperString: Easiest way would be to assign all the results to an array or object and loop through it in your view. After all, PHP in itself is a templating language :)
or use AJAX and json_encode the data on the php side. i would try to avoid smarty
1

in short, no you cant, it is a php variable (technically a resource in this case) so you have to parse it through the php engine, which requires the php tags

echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
    echo '<tr><td>'.$row['fruit'].'</td><td>'.$row['id'].'</td></tr>';
}
echo '</table>';

Comments

0

Short answer is no. HTML cannot deal with dynamic content.

Comments

0

If you want to cut down the amount of echo statements within your code you can store the html within a given variable and then make reference to it.

Comments

0

I find it better to do the following:

<table>
<?php foreach($result as $row): ?>

   <tr>
    <td><?php echo $row['fruit']?></td>
    <td><?php echo $row['id']?></td>
   </tr>

<?php endforeach; ?>
</table>

This provides clarity and minimizes concatenation.

Comments

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.