Very often I have heard people suggesting (and I have done it myself too a few times) to keep things separate: PHP code here, HTML there, external CSS, external JS and so on and so on.
Aside from the obvious readibility and maintenance advantages of doing this are there other strong advantages (e.g. in terms of server load or page processing time) in doing it?
As a trivial example, say we want to implement a table containing some products we read from a DB.
The output we want would be something like
<div class="description">This table lists all our products</div>
<table class="products">
<tr>
<th>Name</th>
<th>Available</th>
<th>Price</th>
</tr>
<tr>
<td>Prod 1</td>
<td>Yes</td>
<td>$100</td>
</tr>
...
...
</table>
<div class="info">Some generic info on the products here</div>
So here we have some static output (the 2 div elements and the table header) and some dynamic output (the actual table content).
We could leave all the static things out of PHP tags and try to keep PHP only where needed
<div class="description">This table lists all our products</div>
<table class="products">
<tr>
<th>Name</th>
<th>Available</th>
<th>Price</th>
</tr>
<?
for ($p=0; $p<count($products); $p++)
{
echo '<tr>';
echo '<td>'.$products[$p]["name"].'</td>';
echo '<td>'.$products[$p]["availability"].'</td>';
echo '<td>'.$products[$p]["price"].'</td>';
echo '</tr>';
}
?>
</table>
<div>.....</div>
On the other hand we could embed everything in PHP
<?
echo '<div class="description">This table lists all our products</div>';
echo '<table class="products"><tr><th>Name</th>'.
'<th>Available</th><th>Price</th></tr>';
for ($p=0; $p<count($products); $p++)
{
echo '<tr>';
echo '<td>'.$products[$p]["name"].'</td>';
echo '<td>'.$products[$p]["availability"].'</td>';
echo '<td>'.$products[$p]["price"].'</td>';
echo '</tr>';
}
echo '</table>';
echo '<div>.....</div>';
What are the reasons to choose one over the other?
The alternative syntax for control structures seems to be more readable to me:
<div class="description">This table lists all our products</div>
<table class="products">
<tr>
<th>Name</th>
<th>Available</th>
<th>Price</th>
</tr>
<?php foreach($products as $p): ?>
<tr>
<td><?php echo $p["name"]; ?></td>
<td><?php echo $p["availability"]; ?></td>
<td><?php echo $p["price"]; ?></td>
</tr>
<?php endforeach; ?>
</table>
<div class="info"><?php echo $info; ?></div>
If its just a piece of code for you to play with, it doesn't really matter at all.
But if an application grows more and more complex (and more people work in it), it will usually come to a point where it is vital to separate the view layer (here: HTML) from the code layer (here: PHP) - so you can assign designers to play around with the output and coders to play around with the functionality behind it.
This ain't a php-only topic, this is very general. Architectural models like MVC are based on similar theories.
I think that it is a very compact string <?= $var ?>
I do not suggest to use short sytax of php. Sometimes it can be problem to move code from one server to another.
Reason you need to do so is time. Nice code is simple to support and upgrade. In some cases it is performance issue also, but not in your case.
Ideal example in your case is:
You have to files
index.php
products.php
File products.php contain
<?php
...
foreach($products as $product)
{
$productHTML[] = '<tr><td>' . $product["name"] . '</td></tr>';
}
$productHTML = implode("", productHTML);
?>
index.php:
<html>
...
<?php echo $productsHTML;?>
...
</html>
Ofcourse more advence developers use more hard constructions, we use functions, class, template idea and etc. But such way is enough for small project.
Related
I'm in the process of building an entertainment website. It uses THREE MySQL tables; one called title, one called clips and one called dialogue.
I've been playing around all day with having my PHP fetch data from TWO of the tables (clips and dialogue) and output the content in a HTML table.
I've not had much luck and to cap it all, I was using a free host which has now reached its EP limit and although I've upgraded, I've got to wait 24 hours to try the code I've now come up with.
My question is, have I done it right? Will this collect basic information about the clip and then produce each line of the script in a new TR before going back to the start and collecting information for the next clip?
I really hope this makes sense.
I've tried researching this and have re-built my PHP from the ground up, ensuring that I annotate each section. Last time I checked, it still didn't work!
<table class='container'>";
##############################
# CLIPS QUERY & ECHOING HERE #
##############################
$clipsquery = "SELECT * FROM clips WHERE titleid=$mainurn ORDER BY clipid";
$result2 = mysqli_query($cxn, $clipsquery);
while ($row2 = mysqli_fetch_assoc($result2))
{extract ($row2);
echo "
<tr>
<td colspan='3' class='divider'></td>
</tr>
<tr>
<td class='description'>";
if ($epident == "")
{echo "";}
else
{echo "<span class='episode'>$epident</span>";}
echo "</td>
<td rowspan='2' style='text-align: right'><audio controls>
<source src='media/$clipid.mp3' type='audio/mpeg'>Your browser does not support the audio element.</audio></td>
<td rowspan='2' style='text-align: right'><a href='media/$clipid.mp3' download='$clipid.mp3'><img src='graphics/dl-icon.png' alt='Download Icon' title='Right-click here to download this clip to your computer.'></a></td>
</tr>
<tr>
<td class='description'>$clipsynopsis</td>
</tr>
<tr>
<td colspan='3'></td>
</tr>";
#################################
# DIALOGUE QUERY & ECHOING HERE #
#################################
$dialoguequery = "SELECT * FROM dialogue WHERE clipid=$clipid ORDER BY linenum";
$result3 = mysqli_query($cxn, $dialoguequery);
while ($row3 = mysqli_fetch_assoc($result3))
{extract ($row3);
echo "
<tr>
<td class='speaker'>$speaker:</td>
<td colspan='2' class='script'>$dialogue:</td>
</tr>";}}
echo "
</table>
I've got the site to work (sort of) but the formatting went wild and sometimes included clips from other sources not meant to be on the page!
There are some things I would change in your code. If you trust the variables going into your sql query then change your while loops:
while($row = $result->fetch_assoc()){
$fetchValue = $row['COLUMN_NAME'];
}
I would say you shouldn't be using extract here.
If the user is able to modify the variables going into your sql statement you should implement prepared statements. I would build a class/function and just call it when you need it.
From the HTML/CSS side its probably going to serve you better to use css div tables, especially if you are planning to make the site responsive down the line. This can convert yours
With regards to the queries, I'm not sure I understand the structure of your tables. If you want to keep playing around on your machine install a L/W/M/AMP stack depending on your operating system. See here for more information.
You only need one table where you store the data of clips.
First, you fetch the data into an array, then
you can loop through that array with foreach,
creating the table and filling it with data.
You can use an alternative syntax for foreach to make mixing PHP with HTML easier.
//Creating the array of clips
$clips = [];
$sql = "SELECT * FROM clips";
if($result = mysqli_query($db, $sql)) {
while($row = mysqli_fetch_assoc($result)) {
array_push($clips, $row);
}
}
?>
<!-- Looping through the array and creating the table -->
<table class="container">
<?php foreach ($clips as $clip): ?>
<tr>
<td colspan='3' class='divider'></td>
</tr>
<tr>
<td class='description'>
<span class='episode'><?php echo $clip["id"]; ?></span>
</td>
<td rowspan='2' style='text-align: right'>
<audio controls>
<source src='<?php echo "media/". $clip["id"]. ".mp3"; ?>' type='audio/mpeg'>
Your browser does not support the audio element.
</audio>
</td>
<td rowspan='2' style='text-align: right'>
<a href='<?php echo "media/". $clip["id"]. ".mp3"; ?>' download='<?php echo $clip["id"]. ".mp3"; ?>'>
<img src='graphics/dl-icon.png' alt='Download Icon' title='Right-click here to download this clip to your computer.'>
</a>
</td>
</tr>
<tr>
<td class='description'>
<?php echo $clip["sypnosis"]; ?>
</td>
</tr>
<tr>
<td class='speaker'>
<?php echo $clip["speaker"]; ?>
</td>
<td colspan='2' class='script'><?php echo $clip["dialogue"]; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
You need 1 MySQL table (clips) with the 4 attributes.
You should consider using PDO over mysqli, because it's a better way of dealing with the database.
Also, template engines like Smarty can help you make the code more readable and modifiable, separating the application logic from the presentation logic.
you must use JOIN in your Sql query
SELECT
clips.clipid, clips.columnname,
dilogue.id, dialogue.columnname
FROM
clips JOIN dialogue ON
clips.clipid = dialogue.id
WHERE
clipid=$clipid
ORDER BY linenum
then you can use
while($row = mysqli_fetch_assoc($result)){
echo $row['column name in clips table'];
echo $row['column name in dialogue table'];
}
but you must use Prepared statements or
mysqli_real_escape_string()
to avoid Sql Injections
also open and close PHP tags before and after html)
I'm currently working on a table that contains 'Name', 'Info', 'Price' and 'Duration'. However the PHP-Script is connected to a database.
I want to autofill the tablecells: 'Name', 'Price', 'Duration' via the Database by using PHP and SQL and that works perfectly fine for me. Though, I want to customize the content that's in the individual Info cells (e.g. Readmore jQuery and redirect to other pages).
I tried a little bit with using tags inside the Database and other weird stuff which, obviously, didn't work.
Is there a more elegant way of solving my problem than setting up a complete normal table without PHP/SQL, where I'd have to put in every bit of data about Name,Price and Duration manually?
<table class="table table-bordered table-hover tablesorter row sortable">
<thead>
<tr>
<th class="header">Name</th>
<th class="hidden-xs">Info</th>
<th>Price (in Euro)</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
<?php
//Connect to Database
$db=mysql_connect ("xxxx", "xxxx", "xxxx") or die ('Oops! Da hat wohl' . mysqli_error(). 'Mist gebaut');
//Choose Database
$mydb=mysql_select_db("massageke_de");
//Query Database
$sql="SELECT * FROM Angebote";
//-run the query against the mysql query function
$result=mysql_query($sql);
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$row['Info'];?<</td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Thanks in advance for helping.
Don't bother asking me additional questions.
P.S.: I hope you can help, without needing the CSS of Bootstrap, that I used.
P.P.S.:I know that my PHP-Script is not protected against PHP-Injection
(but I want to and will learn how to secure it)
Edit: As Jester asked for it. I made it quickly with photoshop because I think an image can express much better, what I want to achieve, than my poorly coding-skills.
Get to the image
Seems to me like the easiest way would be to just edit the info column in the database for each? If you want to do it in php i'd suggest making an array using the names (ids would be better but it seems you don't have access to those?) as keys:
$info['Aroma Teilkoerper'] = "Text about aroma teilkoerper";
$info['Aroma Ganzkoerper'] = "Text about aroma ganzkoerper";
and so on until you have all. Then in the loop:
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$info[$row['Name']];?></td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
Hoping that is a workable solution for you? (also you had a syntax error in your closing php tag.
echo $Name =$row['Info'];?< // <----- should be ?> of course
I will have to mention first that I have searched for a Google and stackoverflow and anywhere else, as well as tried to use scripts given in forums and write my own ones, but nothing worked for me. I am completely stuck.
So, all I try to do is to write a script that will delete checked rows from MySQL table. Here is my HTML written inside of a PHP file:
<tr class="noP">
<td class="check"><input class="checkbox" name="checkbox[]" type="checkbox" value="'.$row["PID"].'"/></td>
<td class="id">'.$row['PID'].'</th>
<td>'.$row["name"].'</th>
<td>'.$row["surname"].'</th>
<td>'.$row["pcode"].'</th>
<td class="address">'.$row["address"].'</th>
<td class="email">'.$row["email"].'</th>
<td>'.$row["phone"].'</th>
<td class="education">'.$row["education"].'</th>
<td class="remarks">'.$row["remarks"].'</th>
</tr>
for here $row = mysql_fetch_assoc($qParts);, so this array is just a collector of field values from MySQL DB.
Basically, all I try to do is just a table with all the participants listed with ability to delete selected ones.
I would highly appreciate any help provided. Thank you!
This should help you:
foreach($_REQUEST['checkbox'] as $val)
$delIds = intval($val);
$delSql = implode($delIds, ",");
mysql_query("DELETE FROM table WHERE PID IN ($delSql)");
So, that takes your input array from $_GET/$_POST, sanitises it (a little), then implodes it to get a list of IDs (e.g. 5, 7, 9, 13). It then feeds that into an SQL statement, matching on those IDs using the IN operator.
Note that you should do this using prepared statements or similar. It's been a while though, so I can't write them off-hand, but this should give you the gist of it.
To do this using PDO, have a look here. It's a bit more complex, since you need to dynamically create the placeholders, but it should then work the same.
Reference - frequently asked questions about PDO
I think I can help you out. I had the same issue during my semester project. The problem can be solved using HTML and PHP alone.
I am assuming that PID is the primary key in your table. The trick here is to put the entire table in a form so that it looks like this:
<form action="/*NAME OF THIS PAGE HERE*/.php" method="POST">
<?php
if(isset($_POST['delete'])) //THE NAME OF THE BUTTON IS delete.
{
foreach ($_POST["checkbox"] as $id){
$de1 = "DELETE FROM //table-name WHERE PID='$id'";
if(mysqli_query($conn, $de1))
echo "<b>Deletion Successful. </b>";
else
echo "ERROR: Could not execute";
}
}
if(isset($_POST['delete'])){
echo"<b>Please make a selection to complete this operation.</b>";
}
?>
</br>
<!-- below you will see that I had placed an image as the delete button and stated its styles -->
<button type="submit" name="delete" value="delete" style="float:right;border:none; background:none;">
<img style="width:55px; height:55px;margin-left:10px; margin-bottom:6px; float:left;" src="images/del.png">
</button>
<table>
<thead>
<tr>
<th>#</th>
<th>PID</th>
<th>NAME</th>
<th>SURNAME</th>
<!--REST OF THE TABLE HEADINGS HERE -->
</tr>
<?php $fqn="SELECT * FROM //table-name here;
$fqn_run=mysqli_query($conn,$fqn);
while($row=mysqli_fetch_array($fqn_run)):?>
</thead>
<tbody>
<tr class="noP">
<td class="check"><input class="checkbox" name="checkbox[]" type="checkbox" value="<?php echo $row["PID"];?>"></td>
<td><?php echo $row['PID'];?></td>
<td><?php echo $row["name"];?></td>
<td><?php echo $row["surname"];?></td>
<!-- REST OF THE ROWS HERE -->
</tr><?php endwhile;?>
</tbody>
</table>
</div>
</div>
</form>
Hope this helps you.
I am likely to get b'*ch slapped because I haven't searched the forum enough before posting, but I really think I searched all relevant posts already, many seem not specifically covering the question I have, the others fly right over my beginner's head ( as I am new to PHP & js ). That being said...
I have built a PHP code to fetch data from an XML file using the $xml=simplexml_load_file();
No worries there, however one of the needed data 'entries' or 'fields' needs to exist within an onclick and/or an onmouseup javascript function.
The code is as follows:
<?php
$xml=simplexml_load_file('prod_test_feed_sameday.xml');
$max = 8;
$i = 1;
foreach($xml->product as $feed){
if ($i <= $max){
echo "<table id='{$feed->position}' class='prod_container'>
<td class='hidden_mask' id='{$feed->position}'>
</td>
<td class='hidden_image' id='{$feed->position}'><span style='background:url({$feed->prod_image_large}) no-repeat center;'/></span><div><a onmouseup='$('.hidden_image#{$feed->position}').slideToggle('slow');' onclick='$('.hidden_mask#{$feed->position}').hide();'><b>CLOSE</b></a></div>
</td>
<tr>
<td class='prod_image' id='{$feed->position}'>
<span style='background:url({$feed->prod_image_small}) no-repeat center; background-size:contain;'/></span>
</td>
<td rowspan='1' class='info_toggle' id='{$feed->position}'><a onmouseup='$('.hidden_image#{$feed->position}').slideToggle('slow');' onclick='$('.hidden_mask#{$feed->position}').show();><img src='images/zoom_02.png' title='See a larger image of these flowers' /></a>
</td>
</tr>
<tr>
<td colspan='2' class='prod_name' id='{$feed->position}'>{$feed->prod_name}
</td>
</tr>
<tr>
<td colspan='2' class='prod_price' id='{$feed->position}'><span id='{$feed->position}'>from: £{$feed->price}</span><a href='{$feed->prod_link}' target='_blank'><span class='buy_button'> Buy it now! </span></a></td>
</tr>
</table>";
$i++;
}
}
?>
The data and the CSS all work perfectly. There is a href link towards the end of the code, which also works perfectly.
I am racking my brain trying to find the error in my syntax within the onlick function.
I have tried all manners of backslashing, using trial and error, for exampel:
onclick='$(\'.hidden_mask#{$feed->position}\').hide();' or
onclick='\'$('.hidden_mask#{$feed->position}').hide();\'' or
onclick=\''$(\'.hidden_mask#{$feed->position}\').hide();\'' or even
onclick=\''$(\\'.hidden_mask#{$feed->position}\\').hide();\'' <--Freddy Krugar 'slashing' example
At any rate I am at a loss.
Try with double quotes and escape them:
echo " ...
onclick=\"$('.hidden_mask#{$feed->position}').hide();\"
...";
Or
echo " ...
onclick='$(\".hidden_mask#{$feed->position}\").hide();'
...";
DEMO
This way you do the escaping in the PHP only, without needing the Freddy Krugar escaping for the DOM parser.
I have a table that is created using PHP and when you click on the name of the item I want the description to show.
<table border="1" bordercolor="#000000">
<tr class="trintial">
<th width="50px"><input type="checkbox" readonly="readonly" checked="checked" /></th>
<th width="300px">To-Do Item</th>
<th width="100px">Priority</th>
<th width="100px">Due Date</th>
</tr>
<?php
$i=0;
while ($i < $num)
{
$entrynum=mysql_result($result,$i,'todo.entry');
$f2=mysql_result($result,$i,'todo.item');
$f3=mysql_result($result,$i,'todo.priority');
$f4=mysql_result($result,$i,'todo.duedate');
$f5=mysql_result($result,$i,'todo.description');
?>
<tr id="<?php echo "row$entrynum"; ?>" class="trintial">
<td><input type="checkbox" onchange="change(this,<?php echo "row$entrynum"; ?>)" name="<?php echo "box$entrynum"; ?>" value="checked" /></td>
<td><?php echo $f2; ?></td>
<td><?php echo $f3; ?></td>
<td><?php echo $f4; ?></td>
</tr>
<?php
$i++;
}
mysql_close($con);
?>
</table>
i need it to ouput when the text of $f2 is clicked
I like this view of the world. You really can't do that. Because what you don't echo with PHP, the user never receives in his browser. (Remember: PHP is executed server-side only, HTML, CSS, JavaScript are "executed" in the users browser.)
To make your description appear when $f2 is clicked, you'll need to pack it into your html and then hide it with CSS. After that you'll need to write some smart JavaScript which overwrites the CSS of your description, when $f2 is clicked. That's not trivial, but it's doable. If you need some help with it, post exactly what you understand under "show"ing the description, because there are lots of ways to do this.
Supertech, I get the impression that you are confusing server-side code (PHP in this case) with client-side code. PHP doesn't run in the user's browser. Once the page data has been sent, PHP is no longer running. What you want to do is create some Javascript to modify the style (CSS) of the elements on the page.
Start by outputting your table as it would look with everything expanded. Once this is done, add a CSS class to all of the elements, such as "hidden". Then in your CSS for the page, define this class with something like this
.hidden {
display:none;
}
Now, you need to add the appropriate Javascript to links to display. Something like this should do
Click Me
If all is well, yourelement will now be displayed.
You can read up on the CSS display property here:
http://www.w3schools.com/css/pr_class_display.asp
And, the Javascript necessary to change the style here:
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/
I hope this helps you understand how all of these essentially unrelated pieces fit together in your web application.