3

My website consists of many products that are each contained in a div with the id content block. The link, image, background, description and price are all loaded from a mySQL table. My original plan was to save the below html code as a string and loop over the rows in the mySQL table filling the string I created with php/mySQL values.

I was wondering if I am going about this the right way, or is there a better way to create html code from php variables?

<div id="contentblock" style="background-image:url(images/$BACKGROUND.png);">
    <div id="picture"><a href="$LINK"><img src="$IMAGELINK"/></a></div>
    <div id="description"><p>$DESCRIPTION</p></div>
    <div id="price"><p class=price>$PRICE</p></div>
</div>
6
  • Is this code block part of a loop? Commented Jun 26, 2012 at 0:17
  • 1
    Depending on how frequently you reuse this, you could create a class which takes the Id or Data row and has a GenerateHtml() method. This would give you cleaner code but may be needless overhead if its only used in a few places Commented Jun 26, 2012 at 0:17
  • 1
    sounds relatively standard, if you don't want to use a template engine. Commented Jun 26, 2012 at 0:17
  • Incidentally, be careful manipulating strings in memory as strings are immutable - better to output directly if you're generating a large page Commented Jun 26, 2012 at 0:18
  • Could you provide more info on a template engine? that seems to be what I am after. EDIT: it seems that my original plan is very similar to a template generator. Commented Jun 26, 2012 at 0:19

4 Answers 4

7

Firstly PHP is a template engine - in my experience template engines that layer ontop of PHP are only good for the simplest of cases and are easily outgrown.

Secondly the original code is as good as any method. At risk of stating the obvious to make it better abstract it into a function;

function output_block($BACKGROUND, $LINK, $IMAGELINK, $DESCRIPTION, $PRICE)
{
    echo "<div id='contentblock' style='background-image:url(images/$BACKGROUND.png);'>
        <div id='picture'><a href='$LINK'><img src='$IMAGELINK'/></a></div>
        <div id='description'><p>$DESCRIPTION</p></div>
        <div id='price'><p class=price>$PRICE</p></div>
    </div>";
}

If you want to make it much better then adopt a framework, an entire admin config page is show below. All of the HTML glue is provided by the framework - the following code is real, but really to illustrate how a framework can provide a lot of the grunge work for you.

In the example below if I want to edit a single entity I'd change the TableViewEdit into a FormView and provide an instance of an entity rather than an iterable list.

$entity = new CbfConfig();  // Database entity
$page = new AdminWebPage("Site Configuration"); // Page for output

/*
 * build the view
 */
$vil = new ViewItemList();

$col = &$vil->add(new ViewItem("description","Description"));
$col->get_output_transform()->allow_edit(false); // this field cannot be editted
$col = &$vil->add(new ViewItem("value","Value"));

$v1 = new TableViewEdit($entity, $vil,"admin_values"); // present as standard editable table

/*
 * output the page
 */
$page->begin();
$iterable_list = CbfConfig::site_begin();
$page->add_body($v1->get_output($iterable_list,'admin_config'));
$page->end();
Sign up to request clarification or add additional context in comments.

Comments

3

Id just have all my html code outside of php tags, then whereever I need a variable from php do as follows

<div id="description"><p><?php echo $DESCRIPTION; ?></p></div>

You can loop around non php code too. For example

<?php

for($i = 0; $i < 10; $i++) {
?>
<div id="description"><p><?php echo $i; ?></p></div>
<?php
} //end for loop
?>

Obviously this is just an example.

4 Comments

I do not know how many products there will be, so the html code must be generated in php
Ive reedited my post to show how you can loop around non php code in php. This way you dont need tow orry about storing the html itself in variables.
@JonTaylor You'd be better to give a foreach($RecordSet as $Row) {} example - That way, you don't need to guess/read the record count and it's more readable
@Basic I agree, however I was simply giving an example of using a loop around non php code. I think its far more beneficial to someone learning to show them the basics and have them figure out the rest.
1

well if im without a template engine for somereason i usually do something like:

function partial($file, $args = array()) {
  extract($args);
  ob_start();
  include($file);
  return ob_get_clean();
}

Comments

0

Really, there are 3 ways of doing this. Use whichever is easiest for you in the context that you are using it in.

<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
    echo "<div>{$row['fieldName']}</div>";
}
?>

<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
    echo '<div>'.$row['fieldName'].'</div>';
}
?>

<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
?>
    <div><?= $row['fieldName']; ?></div>
<?php
}
?>

8 Comments

could concatenate a variable and echo it once.
In general, you want to avoid doing that. Memory usage can spike a lot if you're storing all your data into a variable instead of echoing it out as you receive it.
If that's the case, you'd better get a new server!
paul is right, in general if there is a memory usage issue with this approach, then there are other problems. Also it is faster (very slightly) than the multiple echo version
@Dagon doing it per-row is not too bad but generating a whole page by concatenating into a string is a huge waste of resources for no advantage - you lose all the benefits of streaming as well as leaving hundreds of copies of a string lying about. I agree it's not a prime consideration but why do it unless there's a really good reason?
|

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.