user1104233
user1104233

Reputation: 31

PHP Includes & MySQL into webpage w/ Dynamic Variables

I Have a standard HTML table saved into a PHP file which I am putting on many webpages, but each webpage is about a different item.

So in my HTML table (in the blanktable.php file, which I include on the webpages) I've put in undefined PHP variables like so:

    <table>
<tr>
    <td>Item Name:</td>
    <td><?php echo "$name"; ?></td>
</tr>
<tr>
    <td>Price:</td>
    <td><?php echo "$price"; ?></td>
</tr>
<tr>
    </table>

What would be the best way to dynamically create my webpages, so all I would have to do is define the variables instead of hardcoding the HTML each time?

Upvotes: 3

Views: 139

Answers (3)

ppp
ppp

Reputation: 2055

You must prepare the variables first, and then include the blanktable.php file for every separate item.

Get the products from your database with something like:

$query = "SELECT * FROM items";
$result = mysql_query( $query ) or die( mysql_error() );

Then define the variable values and include the blanktable.php file for each item in your database table to display it.

while( $row = mysql_fetch_array( $result ) ){
    $data['name'] = $row['name'];
    $data['price'] = $row['price'];
    include "table.php";
    }

Upvotes: 0

jb11
jb11

Reputation: 557

Assuming you have a mySQL database you would have something like:

    <table>
    <?php
    $results = mysql_query("SELECT * FROM products WHERE id=1");
    $data = mysql_fetch_assoc($results);
    ?>
    <tr>
        <td>Item Name:</td>
        <td><?php echo $data['name']; ?></td>
    </tr>
    <tr>
        <td>Price:</td>
        <td><?php echo $data['price']; ?></td>
    </tr>
    <?php
    }
    ?>
    </table>

Upvotes: 1

Alex
Alex

Reputation: 34978

You can load $name and $price from your database and then include your blanktable.php. By this, the table will be filled with the actual values.

Upvotes: 1

Related Questions