PDA

View Full Version : [FAQ] How to populate HTML elements with PHP



Spudinski
04-07-2008, 04:27 PM
Well, it's commonly asked upon the beginners, so I'll go a bit into this subject.
Some people use javascript to do this, even if they have an PHP enabled web server, which is good, but it is not the only technique to do it.
I will try to provide the best explanation over a few examples.

Example 1
Making a select on an page, which lists all the flowers available at the shop.


<?php
// Just the normal select element
echo '<select name="flowers" onchange="document.forms[0].post()">';
// The mysql query
$sql_text = 'SELECT `id`, `name` FROM `flowers` ORDER BY `name` DESC';
// Execute the query
$query = mysql_query($sql_text);
// To solve a bug where you cannot select the first element
echo '<option disabled="disabled">' . mysql_num_rows($sql_txt) . ' Flowers</option>';
// Loop trough the results
while($flower = mysql_fetch_assoc($query)) {
// Echo the results out into option elements
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
// Close the select element
echo '</select>';
?>

Example 2
Displaying a list of item categories.


<?php
// Start the ul element
echo '<ul>';
// The mysql query
$sql_text = 'SELECT `cat_name` AS `name` FROM `categories` ORDER BY `cat_id`';
// Execute the mysql query
$query = mysql_query($sql_text);
// Loop trough the results
while($cat = mysql_fetch_assoc($query))
// Echo out the category name
echo ' ' . $cat['name'] . '';
// Close the ul element
echo '[/list]';
?>

Example 3
Say you want to make something like a forum, and you need to display the categories and the boards within the categories.


<?php
// The query to retrieve the categories
$cat_sql_text = 'SELECT `cat_name` AS `name`, `cat_id` AS `id` FROM `categories` ORDER BY `cat_id` DESC';
// Execute the mysql query
$cat_query = mysql_query($cat_sql_text);
// Loop trough the categories
while($cat = mysql_fetch_assoc($cat_query)) {.
// Make a table element, aswell as display the category name
echo '

<table id="' . $cat['id'] . '">
<tr><th>' . ucwords($cat['name']) . '</th></tr>';
// Get the boards from the category
$board_sql_text = 'SELECT `board_name` AS `name`, `board_id` AS `id`, `board_description` AS `description`' .
' FROM `boards` WHERE `board_id` = \'' . $cat['id'] . '\'';
// Execute the query
$board_query = mysql_query($board_sql_text);
// Loop trough the boards
while ($board = mysql_fetch_assoc($board_query)) {
// Display the board name, and description
echo '<tr><td id="' . $board['id'] . '">' .
'' . $board['name'] . '
' . $board['description'] .
'</td></tr>';
}
// Close the table and paragraph elements
echo '</table></p>';
}
?>

Hope this gives an idea of how to do this, if not - please reply to this thread with your question.

threeZ
06-13-2008, 04:35 PM
Example 1
Making a select on an page, which lists all the flowers available at the shop.


<?php
// Just the normal select element
echo '<select name="flowers" onchange="document.forms[0].post()">';
// The mysql query
$sql_text = 'SELECT `id`, `name` FROM `flowers` ORDER BY `name` DESC';
// Execute the query
$query = mysql_query($sql_text);
// To solve a bug where you cannot select the first element
echo '<option disabled="disabled">' . mysql_num_rows($sql_txt) . ' Flowers</option>';
// Loop trough the results
while($flower = mysql_fetch_assoc($query)) {
// Echo the results out into option elements
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
// Close the select element
echo '</select>';
?>


good example. but just as a heads up, you can insert raw html within your php files :)
example:

<select name="flowers" onchange="document.forms[0].post()">
<?php
$sql_text = 'SELECT `id`, `name` FROM `flowers` ORDER BY `name` DESC';
// Execute the query
$query = mysql_query($sql_text);
// To solve a bug where you cannot select the first element
echo '<option disabled="disabled">' . mysql_num_rows($sql_txt) . ' Flowers</option>';
// Loop trough the results
while($flower = mysql_fetch_assoc($query)) {
// Echo the results out into option elements
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
?>
</select>

your host and php installation will thank you :wink:

Spudinski
06-13-2008, 05:26 PM
Actually, that style of programming is not correct under PEAR coding standards.
You should only use opening - and closing - php tags for large blocks of HTML markup, for single lines echo(or print) is effective enough.
My way gives the script a "clean" and simple look.

Floydian
06-13-2008, 06:25 PM
I agree with Spudinski on this one. Using opening and closing tags is definitely less efficient, especially if you have a lot of them.

And indeed, a clean and simple looking script has benefits that far outweigh the nonexistant bonus that starting and ending php tags would give you if they did give you a bonus.

threeZ
06-13-2008, 06:56 PM
why don't you try benchmarking the two ;)

Anonymous
06-13-2008, 07:40 PM
**<?php ?>**<?php ?>**<?php ?>**<?php ?>**

-- Condensed for brevity - it's Friday, and I'm feeling lazy ;)

vs.



echo str_repeat("**", 10000);



Any takers? ;) I know which I'd choose.

Context switching is *always* a bad idea unless it is a one off

threeZ
06-13-2008, 07:52 PM
**<?php ?>**<?php ?>**<?php ?>**<?php ?>**

-- Condensed for brevity - it's Friday, and I'm feeling lazy ;)

vs.



echo str_repeat("**", 10000);



Any takers? ;) I know which I'd choose.

Context switching is *always* a bad idea unless it is a one off


sorry but your example provides no relevancy to the argument.
you can't str_repeat(); <select> 1000 times.
Simply, your server and php installation can parse html faster when presented in "raw" format than echoed via php.

Logically:
html -> php -> apache
echo ("<table><tr><td>");

opposed to:
html -> apache
<table><tr><td>

Anonymous
06-13-2008, 08:10 PM
Perhaps not immediately obvious, but my example was more to demonstrate the foolishness of context switching.

The core principle of a fair number of applications is:

* validate input
* data retrieval
* application logic
* display data

My argument follows that:

Mixing these up is not the best of solutions as it makes for more complex source (although Spud has presented some pretty readable source), makes it a lot more difficult for language (both spoken and programming) translation, and I won't even mention changing database libraries.

As for str_repeat, well there is one notable application I use which uses that very construct - okay, I agree, not <select>, but <option> - Surprised me, but it works rather well :)

We digress again - perhaps you should join us in chat - I hate hijacking topics :D (Soz, Spud)

Sneaky - editing whilst I replied .. Yes logically, but not physically - the page will still be processed through PHP (assuming the content disposition is correct)

Spudinski
06-13-2008, 08:33 PM
why don't you try benchmarking the two ;)


Tested with:

<?php

$array = array();
$init_time = array();
$endtime = array();

for($i=1;$i<=50000;$i++) $array[] = array('id' => $i, 'name' => 'name' . $i);

$init_time[0] = microtime();
echo '<select name="flowers" onchange="document.forms[0].post()">';
$query = $array;
echo '<option disabled="disabled">' . mysql_num_rows($sql_txt) . ' Flowers</option>';
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
echo '</select>';
$endtime[0] = microtime();


//vs.


$init_time[1] = microtime();
?>
<select name="flowers" onchange="document.forms[0].post()">
<?php
$query = $array;
echo '<option disabled="disabled">' . mysql_num_rows($sql_txt) . ' Flowers</option>';
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
?>
</select>
<?php
$endtime[1] = microtime();

$init_time[3] = explode(' ', $init_time[0]);
$init_time[3] = $init_time[3][0];
$endtime[3] = explode(' ', $endtime[0]);
$endtime[3] = $endtime[3][0];
$endtime[3] = $endtime[3] - $init_time[3];
$init_time[4] = explode(' ', $init_time[0]);
$init_time[4] = $init_time[4][0];
$endtime[4] = explode(' ', $endtime[0]);
$endtime[4] = $endtime[4][0];
$endtime[4] = $endtime[4] - $init_time[4];

echo 'Spudinski\'s method: ' . $endtime[3] . ' seconds' . "\n" .
'threeZ\'s method: ' . $endtime[4] . 'seconds.';

?>


There is "no" difference in performance from what I can see.

Spudinski's method: 0.397759 seconds.
threeZ's method: 0.397759 seconds.

Now this is anotehr thing we can lay to rest.

Floydian
06-14-2008, 02:50 AM
If there is no difference, then one can look to other factors such as the readability of the code which in my opinion can be pretty unreadable with lots of php tags in the html



<input type="text" name="blah<?php echo $some_id_here; ?>" id="do_js_script('<?php echo $some_function_name; ?>', '<?php echo $some_random_variable; ?>', '<?php echo $another_rand_variable; ?>')" value="<?php echo $and_another_variable; ?>">


or


<?php
echo <<<EOT
<input type="text" name="blah{$some_id_here}" id="do_js_script('$some_function_name', '$some_random_variable', '$another_rand_variable')" value="$and_another_variable">
EOT;
?>

Take your pick for which is more readable....

And something like this is way to small to have any substantial impact on performance either way you go, so I should think the "other" factors should be the determining factor here.

One should also take note of the need for five echos in the first code snippet, and only one echo in the second one....

threeZ
06-16-2008, 07:02 PM
umm, i don't believe you went about that quite correct :)


0.000747 vs. 0.000639
difference of 0.000108 in threeZ's favor

0.000757 vs. 0.000646
difference of 0.000111 in threeZ's favor

0.000736 vs. 0.000633
difference of 0.000103 in threeZ's favor

might have to refresh once or twice to see the difference
18/20 times "my" method is faster. granted we are speaking very small increments but, with larger snippets = larger results etc.


<?php
$array = array();
for($i=1; $i<=300; $i++) $array[] = array('id' => $i, 'name' => 'name' . $i);

$t1 = explode(' ', microtime());
echo '<select name="flowers" onchange="document.forms[0].post()">';
echo '<option disabled="disabled">Flowers</option>';
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
echo '</select>';
$t2 = explode(' ', microtime());
$r1 = $t2[0] - $t1[0];
?>
<?php
$t3 = explode(' ', microtime());
?>
<select name="flowers" onchange="document.forms[0].post()">
<option disabled="disabled">Flowers</option>
<?php
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
?>
</select>
<?php
$t4 = explode(' ', microtime());
$r2 = $t4[0] - $t3[0];

$d = ( ($r1 > $r2) ? $r1 - $r2 : $r2 - $r1 );
echo '
'. $r1 .' vs. '. $r2 .'
difference of '. $d .' in '. ( ($r1 > $r2) ? 'threeZ' : 'Spudinski' ) .'\'s favor
';
?>

threeZ
06-18-2008, 10:43 AM
[15:57] <Spudinski> anyways threeZ, your post was really inconclusive.
[16:02] <&Nyna> I thought that - although why you are trying to shave microseconds off a simple html page is beyond me ;)

how's this for conclusive...
i've seperated both snippets and timed php.exe executing both of them.


<?php
$t1 = microtime(true);
system('C:/php5/php.exe C:/www/test.php');
$t2 = microtime(true);
$r = $t2 - $t1;
echo 'threeZ: '. $r;

$t1 = microtime(true);
system('C:/php5/php.exe C:/www/test_echo.php');
$t2 = microtime(true);
$r = $t2 - $t1;
echo 'Spudinski: '. $r;
?>

result:


threeZ: 2.9573328495026
Spudinski: 3.3081579208374

EDIT:
Spud's responce ->

[06:46:08] <@Spudinski> there could be a hell load of reasons for it being almost a seond slower, but it's not the script I presented.
[06:46:25] <@Spudinski> it's impossible, it has to be one of your PHP addons.
[06:46:42] <&Nyna> ~giggle~
[06:47:08] <+threeZ> lol
[06:47:13] <+threeZ> i don't have any php addons ;)

testing on my local machine:
Intel(R) Core(TM)2 CPU
T5300 @ 1.73GHz
1.73 GHz, 2.00 GB of RAM
and no "php addons"

test.php

<?php
$array = array();
for($i=1; $i<=300; $i++) $array[] = array('id' => $i, 'name' => 'name' . $i);
?>
<select name="flowers" onchange="document.forms[0].post()">
<option disabled="disabled">Flowers</option>
<?php
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
?>
</select>

test_echo.php

<?php
$array = array();
for($i=1; $i<=300; $i++) $array[] = array('id' => $i, 'name' => 'name' . $i);
echo '<select name="flowers" onchange="document.forms[0].post()">';
echo '<option disabled="disabled">Flowers</option>';
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
echo '</select>';
?>

anyways, as stated on the IRCd.. im done proving myself and i'm done with this forum. it was nice but, meh
the argument has gone from "threeZ is wrong" to "why would you want to do that anyway?!".
pick a side and stick to it..and when you're proven wrong -> admit to it plz, have a little bit of character.
im out.

Anonymous
06-18-2008, 11:03 AM
<?php
$array = array();
for($i=1; $i<=300; $i++) $array[] = array('id' => $i, 'name' => 'name' . $i);

$t1 = explode(' ', microtime());
echo '<select name="flowers" onchange="document.forms[0].post()">';
echo '<option disabled="disabled">Flowers</option>';
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
echo '</select>';
$t2 = explode(' ', microtime());
$r1 = $t2[0] - $t1[0];
?>
<?php
$t3 = explode(' ', microtime());
?>
<select name="flowers" onchange="document.forms[0].post()">
<option disabled="disabled">Flowers</option>
<?php
foreach($array as $flower) {
echo '<option value="' . $flower['id'] . '">' . $flower['name'] . '</option>';
}
?>
</select>
<?php
$t4 = explode(' ', microtime());
$r2 = $t4[0] - $t3[0];

$d = ( ($r1 > $r2) ? $r1 - $r2 : $r2 - $r1 );
echo '
'. $r1 .' vs. '. $r2 .'
difference of '. $d .' in '. ( ($r1 > $r2) ? 'threeZ' : 'Spudinski' ) .'\'s favor
';
?>


Well, there's a surprise - he's right.

10,000 runs produced a total time difference of 0.000949442 seconds faster for ThreeZ. Well bugger me with a blunt vegetable - let me quickly write home about that one.

That was running on a dedicated (non-connected) 64-bit BSD box running PHP5, with all bar the critical system services stopped and in stand-alone mode.