How to style the output of an echo to display a grid? - php

My team and I have made a database in php my admin for a restaurant, and I'm currently working on the customer dashboard. Im using for each loops to display complete orders in one of the dashboard tabs, and have the code working, but right now it just outputs regular black text. I was wondering how to style it to output the rows as a grid, similar to bootstrap grids.
I've tried to just add containers with rows and columns to the foreach echo itself, but its just not working as I thought it would.
<div id="CurrentOrders" class="tabcontent" style="margin-left: 24px">
<!-- This information will be pulled from the Orders table in the DB -->
<h3>Current Orders</h3>
<p>
<div class="container">
<?php
foreach ($orderno as $order) {
$n = $order['OrderNo'];
$menunamequery = "SELECT * FROM OrderItem WHERE OrderNo = '{$n}'";
$currentorders = getRows($menunamequery);
foreach ($currentorders as $currentorder) {
echo "Order Number -"." ".$currentorder['OrderNo']." , "."Order -"." ".$currentorder['MenuName']." , "."Quantity -"." ".$currentorder['Quantity']."<br>";
}
}
?> </div>
</p>
</div>
The expected result is for these rows im outputting to have some sort of grid layout, the actual result is just plaintext currently.
Sorry if this is a bad question, my team and I just learned php this semester and are hoping to continue getting better at it. Any help would be appreciated.

You can simply output HTML from PHP:
echo '<span style="color: red">'.$currentorder['MenuName'].'</span>';
However, it is advised that you sanitize your output, so nobody can "create HTML" by putting tags in the database;
echo '<span style="color: red">'.htmlspecialchars($currentorder['MenuName']).'</span>';
This does exactly what it says; makes HTML entities from special characters. For example, > will be printed as >, which the browser will safely render as >, instead of trying to interpret it as an HTML element closing bracket.
Alternatively, you can simply write HTML directly if you wish, by closing and opening the PHP tags:
// PHP Code
?>
<span class="some-class"><?=htmlspecialchars($currentorder['MenuName'])?></span>
<?php
// More PHP Code
You may also want to look into templating engines to make it easier for you, although it depends on the project if it's worth it for you to look into that, since there is a little bit of a learning curve to it.

Related

Adding a class to all English text in HTML?

The requirement is to add an englishText class around all english words on a page. The problem is similar to this, but the Javascript solutions wont work for me. I require a PHP example to solve this problem. For example, if you have this:
<p>Hello, 你好</p>
<div>It is me, 你好</div>
<strong>你好, how are you</strong>
Afterwards I need to end with:
<p><span class="englishText">Hello</span>, 你好</p>
<div><span class="englishText">It is me</span>, 你好</div>
<strong>你好, <span class="englishText">how are you</span></strong>
There are more complicated cases, such as:
<strong>你好, TEXT?</strong>
<div>It is me, 你好</div>
This should become:
<strong>你好, <span class="englishText">TEXT?</span></strong>
<div><span class="englishText">It is me</span>, 你好</div>
But I think I can sort out these edge cases once I know how actually iterate over the document correctly.
I can't use javascript to solve this because:
This needs to work on browsers that don't support javascript
I would prefer to have the classes in place on page load so there isn't any delay in rendering the text in the correct font.
I figured the best way to iterate over the document would be using PHP Simple HTML DOM Parser.
But the problem is that if I try this:
foreach ($html->find('div') as $element)
{
// make changes here
}
My concern is that the following case will cause chaos:
<div>
Hello , 你好
<div>Hello, 你好</div>
</div>
As you can see, it's going to go into the first div and then if I process that node, I will be processing the node within that too.
Any ideas how to get around this and only select the nodes for processing once?
UPDATE
I realise now that what I effectively need is a recursive way to iterate over HTML elements with the ability to change them as I iterate over them.
You should travel through siblings that way you won't get in trouble with such a cases...
Something like that:
<?php
foreach ($html->find('div') as $element)
{
foreach($element->next_sibling() as $sibling){
echo $sibling->plaintext()."\n";
}
}
?>
Or much easier way imo:
Just...
Change every <*> to "\n"."<*>" with preg_replace();
Make an array of lines like $lines = explode("\n",$html_string);
3.
foreach($lines as $line){
$text = strip_tags($line);
echo $text;
}

Array contents not displaying well, when placed between certain lines of the code

Whenever I move the codeblock that generates courses with a grade of "F", it does not not echo out the courses that meets the criteria. But when I move it to beginning of the main div header of the script it displays well.. What could the problem be? I actually want it to be at the end of the script for the sake of printing out. I've also checked the source code and the parameters I was looking for wasn't there.
Pastebin of full code
echo "<table bgcolor = red >";
echo "<tr align= \"center\">";
$carry_over = array();
$score_count = mysql_numrows($query8);
echo "<th>"."Failed Courses : "."</th>";
if($score_count !== 0){
while ($row8 = mysql_fetch_assoc($query8)) {
echo"<td>". $row8['course_code']."</td>;
}
}
echo "</tr>\n";
echo "</table>";
There are inconsistencies between your provided example here and the pastebin code you linked to. Which version are you using?
If it's the pastebin version you may be having issues with this line:
echo "<th>"."Failed Courses";
You are missing the </th> tag which could be messing with your output.
It seems like it is going to be a long bit of code so I'm posting it here, I don't intend for this to be an answer to your problem as I can't get it to do what you're saying.
PHP allows for information to be set outside of the PHP tags, and when that happens it is treated as regular HTML.
E.G.
<?php
If(2==2){
?><b>HELLO!</b><?php
}
?>
And
<?php
if(2==2){
echo "<b>HELLO!</b>";
}
?>
Will both result in <b>HELLO!</b> to be output to the screen. This is useful for things that might require a lot of HTML in more than one block, as well as HTML that may require extensive style definitions or other places where double quotes will be needed, for example
<div id="list_row[$i]" class="something something2 something3"> would have to be escaped as
echo <div id=\"list_row[$i]\" class=\"something something2 something3\"> whereas it could just be put more or less intact in php using the above mentioned fact. Now, there would still need to be an echo statement for the $i portion, as I don't think PHP processes the text, but I've never tried it so I can't be sure.
As for your HTML,
<th> tags are meant to be a header, aka in the top part of a table. <td> are meant to be table-data cells.
Seems like you're making a lot of unnecessary calls to the same MySQL tables, and I'm hoping I can condense it down a bit.
Why are you doing this?
echo "<th>"."Failed Courses : "."</th>";
do
echo "<th>"."Failed Courses : </th>";
and also before you do a while loop try to see what your results looks like.
$row8 = mysql_fetch_assoc($query8)
then print_r($row8);
post your results.
Also the table structure should be
<table>
<th></th>
<tr>
<td></td>
</tr>
</table>

How to number things in PHP?

UPDATE:
I know I can use <ol> directky in the output but I remember using something like:
<?php echo $i++; ?> when I worked on a wordpress blog once. Every time I inserted that tag a number greater than the previous appeared so I basically did:
<?php echo $i++; ?> Text
<?php echo $i++; ?> Text
<?php echo $i++; ?> Text
I'm a front end guy (HTML/CSS) so please excuse this basic question. I just need to know what code in PHP I can use to number some text.
Text
Text
Text
into:
Text
Text
Text
Kind of like what <ol> does in html but in PHP.
Updated answer:
You can use a variable as you already do (the example you are posting should already work). Just initialize it using $i = 0;
Old answer:
You have a fundamental misunderstanding here. PHP is a scripting language, not a markup language. PHP does operations like connecting to data sources, calculating, making additions, changing entries in databases, and so on. PHP code, in short, is a series of commands that are executed. PHP has no design elements, tags and formatting options in itself.
PHP can (and usually does) output HTML (Where you have <ol>) to display things.
You can have an array of arbitrary data in PHP, coming from a file or data source:
$array = array("First chapter", "Second chapter", "Third chapter");
you can output this data as HTML:
echo "<ol>";
foreach ($array as $element) // Go through each array element and output an <li>
echo "<li>$element</li>";
echo "</ol>";
the result being (roughly)
<ol>
<li>First chapter</li>
<li>Second chapter</li>
<li>Third chapter</li>
</ol>
It depends on what type of file you are trying to write. Most often, PHP is writing a webpage in HTML, but not always. In HTML, if you want a numbered list, you should use an ordered list (<ol>).
If you're just writing a text file of some kind, incrementing and outputting a variable (like $i in your example) should work.
You mention Wordpress, so it's worth noting that if you worked on a Wordpress template before, you were using dozens of special functions in the Wordpress library, even though you may not have been completely aware that was what you were doing. A lot of the PHP heavy lifting is hidden and simplified for the templating engine, and if your current project is not built on that engine, you will have to do that logic yourself.

How do you prevent inline <?= text ?> statement from messing up the displayed source code?

In PHP, whenever I do something like:
<span>Blah blah HTML</span>
<?= echo $this->foo ?>
<br />
In the source it displays like this:
<span>Blah blah HTML</span>
{$this->foo whatever it is} <br />
Instead of
<span>Blah blah HTML</span>
{$this->foo whatever it is}
<br />
Stuff like this happens all of the time. Inline PHP makes my new lines all wonky and it bothers me. It also happens when you start a full block of PHP within HTML but keep it consistent with the HTML tabbing. For example:
<div id="foo">
<div class="bar">
<?
foreach(whatever)
{
?>
</div>
</div>
Will mess up the formatting of the source and I have to do something like this:
<div id="foo">
<div class="bar">
<?
foreach(whatever)
{
?>
</div>
</div>
If you're worried about formatting of the html. Then you need to add a newline.
<span>Blah blah HTML</span>
<?= echo $this->foo."\n" ?>
<br />
But be careful, this is a dangerous route to go down. Because the next thing you'll worry about is tab indentation. So then you'll add a bunch of \t everywhere. And after a while your code will output a clean and neat html but will be close to unreadable as source code.
So my suggestion. Don't worry to much about it.
For the first question, you can just use the newline character \n
I am not so sure about the second item. May I ask why you are worried about the outputted html? If it is because you are using it to see what is output, may I introduce you to firebug? Firebug will display the DOM tree nice and clean for you (and even keeps it updated with DOM injections).
Just so you know, <?= actually means <?php echo. So you only have to do <?=$username?>
If you want your HTML output to be pretty and you don't want to rely on browser tools like firebug, PHP has a class called Tidy that will do the trick.
ps, short tags ( <?= ?> )have been deprecated. You might want to switch to ( <?php ?> )
View the generated HTML code with a tool, e.g. Firebug, that does formatting automatically.
After installing Firebug, just press the F12 key and select the HTML tab. You can navigate the HTML source using a tree control that pretty prints the markup.
You can use Firebug Lite if you are developing in a browser other than Firefox. Just inject the HTML snippet on the Firebug Lite webpage into your site.
Keep in mind that eliminating extraneous whitespace can improve the performance of your site, so having "minified" HTML isn't necessarily a bad thing.
Unfortunately there's not a lot you can do about it directly. While it's nice for us humans to view source code that's well indented, the HTML spec has always considered white space to be insignificant, and therefore people who develop systems for dealing with HTML often don't consider adding features for finely grained control. Also, PHP is made more flexible by the behavior you described. For example, if it was being used to generate output where white space WAS significant the behavior you described would be desirable.
If you decided that well indented HTML source code was important for you, you'd need to put a system in place around your output to handle the formatting. Rather than output directly, something would intercept your output and automatically handle the formatting for you. Output buffering is one was you could achieve this.
ob_start();
//...
//a bunch of code that echos or prints HTML
//...
$output = ob_get_clean();
echo some_function_or_method_call_to_format_your_html_however_you_want($output);
The implementation of some_function_or_method_call_to_format_your_html_however_you_want if left as an exercise for the reader, although the Tidy functions in PHP might be a good place to start.
There are other approaches you could take as well, for example routing all output through an object that, by context, could determine how many tabs or newline to add to the output. The main point is PHP, by itself, isn't going to help you solve this problem, but does provide you with the tools to build your own solution.
the PHP engine replaces areas with PHP code with nothing (except the output from inside php) so when you do:
<h1>Foo Bar</h1>
<?= $value; ?>
<p>my stuff</p>
php removes the newline after ?>. If you want that new line to "be preserved" you can just press enter 2 times after the closing ?>. Really though, if you need to produce HTML output that is "readable" to a human, you should use some library that cleans / sanitizes / formats HTML code (Tidy was mentioned above, so you could use that).
As for your formatting problems with PHP and preserving tabs, the explanation I just gave, covers it - but if you want to make more readable source code (for editing) you should consider using the PHP alternative syntax for templates (which is not really promoted nearly as well as it should be). Most all php control structures (for, while, foreach, if, else) have alternative syntax options which look much prettier in html templates.
<? foreach ($foo as $bar): ?>
<li>
<?= $bar['baz']; ?>
</li>
<? endforeach; ?>
<? if (false == empty($foo)): ?>
<p>
Hello World!
</p>
<? endif; ?>
<? for ($i = 0, $icount = count($foo); $i < $icount; $i++): $val = $foo[ $i ]; ?>
<tr>
<td><?= $val; ?></td>
</tr>
<? endfor; ?>
Also, someone above mentioned that the short tags in PHP are deprecated. That's just an outright falsehood, http://us.php.net/manual/en/ini.core.php#ini.short-open-tag - still alive, kicking, and just as awesome.
Short tags make the above code more readable than having <?php ?> everywhere, not to mention, it makes <?= ?> possible. <?= is the short hand for <?php echo or <? echo - making your code quite more readable. Though, it should be mentioned that if you're writing code that is supposed to be open source and used on a bevy of different webservers, you should at least warn your downloaders that you require short tags to be on (or turn it on via ini_set() or php_flag [in .htaccess])
Will mess up the formatting of the source and I have to do something like this:
<div id="foo">
<div class="bar">
<?
foreach(whatever)
{
?>
</div>
</div>
It's important that the original PHP source code is readable, so that you can maintain it easily. It's not at all important to make all the indenting pretty for the 0.0001% of people who will ‘view source’. The above snippet just makes things harder for you.
In the [HTML] source it displays like this:
<span>Blah blah HTML</span>
{$this->foo whatever it is} <br />
It doesn't for me, the newline appears where you expect. But even so, who cares? As long as the markup itself is valid and compact, you're fine.
Look at JimR's example using PHP in the style of well-nested start and end tags. This is a good approach to maintainability as it keeps one consistent hierarchy of code and markup, rather than switching between nested levels of indenting all the time.
For me, this also has the side-effect of giving HTML source with a consistent indent tree. It's one with more empty lines and larger indents than is strictly necessary, but again, who cares? Extra whitespace making the file bigger is not a problem; on-the-fly compression from the likes of mod_deflate will zip that away to nothing.
Note that the ‘alternative syntax’ as used by JimR is not necessary to use this technique, it works perfectly well with braces too and is a matter of personal taste which you choose:
<?php
$replyn= count($replies);
?>
<?php if ($replyn)==0) {?>
<p> (no replies.) </p>
<?php } else { ?>
<h3> Replies </h3>
<?php for ($i= 0; $i<$replyn; $i++) { ?>
<p>
<?php echo(htmlspecialchars($replies[$i], ENT_QUOTES)); ?>
</p>
<?php } ?>
<?php } ?>
(Although personally I use a shortcut function to avoid typing out echo(htmlspecialchars)) all the time. If you're not using htmlspecialchars, you've probably got security problems.)
This example uses full <?php tags so as to run whether or not short tags are allowed. Ultimately though I do agree with JimR that the full tags are, as they stand, a bit of a waste of time.
(It was a good idea to make PHP more compatible with XML's Processing Instructions, but since they never followed through with a way to template PHP tags into attribute values, it's still not really possible to author a PHP page that's also well-formed XML, making the exercise a bit pointless.)

Using regex in php to add a cell in a row

As usual I have trouble writing a good regex.
I am trying to make a plugin for Joomla to add a button to the optional print, email and PDF buttons produced by the core on the right of article titles. If I succeed I will distribute it under the GPL. None of the examples I found seem to work and I would like to create a php-only solution.
The idea is to use the unique pattern of the Joomla output for article titles and buttons for one or more regex. One regex would find the right table by looking for a table with class "contentpaneopen" (of which there are several in a page) and containing a cell with class "contentheading". A second regex could check if in that table there is a cell with class "buttonheading". The number of these cells could be from zero to three but I could use this check if the first regex returns more than one match. With this, I would like to replace the table by the same table but with an extra cell holding the button I want to add. I could do that by taking off the last row and table closing tags and inserting my button cell before adding those closing tags again.
The normal Joomla output looks like this:
<table class="contentpaneopen">
<tbody>
<tr>
<td width="100%" class="contentheading">
<a class="contentpagetitle" href="url">Title Here</a>
</td>
<td width="100%" align="right" class="buttonheading">
<a rel="nofollow" onclick="etc" title="PDF" href="url"><img alt="PDF" src="/templates/neutral/images/pdf_button.png"/></a>
</td>
<td width="100%" align="right" class="buttonheading">
<a rel="nofollow" onclick="etc" title="Print" href="url"><img alt="Print" src="/templates/neutral/images/printButton.png" ></a>
</td>
</tr>
</tbody>
</table>
The code would very roughly be something like this:
$subject = $article;
$pattern1 = '[regex1]'; //<table class="contentpaneopen">etc</table>
preg_match($pattern, $subject, $match);
$pattern2 = '[regex2]'; //</tr></tbody></table>
$replacement = [mybutton];
echo preg_replace($pattern2, $replacement, $match);
Without a good regex there is little point doing the rest of the code, so I hope someone can help with that!
This is a common question on SO and the answer is always the same: regular expressions are a poor choice for parsing or processing HTML or XML. There are many ways they can break down. PHP comes with at least three built-in HTML parsers that will be far more robust.
Take a look at Parse HTML With PHP And DOM and use something like:
$html = new DomDocument;
$html->loadHTML($source);
$html->preserveWhiteSpace = false;
$tables = $html->getElementsByTagName('table');
foreach ($tables as $table) {
if ($table->getAttribute('class') == 'contentpaneopen') {
// replace it with something else
}
}
Is there a reason that you need to use regex for this? DOM parsing would be much more straightforward.
Since a plugin in the scenario you provided is called everytime you load a page, a regex approach is faster than a dom call, that's why a lot of people use this approach. In Joomla's documentation, you can see too why a regex in the provided scenario is better than trying to use a dom approach.
The problem with your solution is that it's tied with Joomla's default template. I don't remember if it uses the same class="contentheading" structure in all templates. If you plan to GPL such an extension, you should be careful about that.
What you're trying to do seems to me as a template override, explained in more details here. Is a much more simpler solution. For example, the php that creates your article title's:
<div class="componentheading<?php echo $this->params->get('pageclass_sfx')?>">
<h2><?php echo $this->escape($this->params->get('page_title')); ?></h2>
</div>
You just need to override the com_content article template, and echo the html for the pdf buttons after the >get('page_title') call. If you don't want to echo the html, you can create a module or a component, import it in the template and after the >get('page_title') you call the methods in your component that show the html.
This component could have various checkboxes "show pdf (yes/no)" and other interesting actions.

Categories