Are tables the same for PHP - php

I am not understanding I have this right now is the tables for html will work with PHP or are they different. I understand how to do tables in HTML with the CSS but I am not to sure with PHP. I am new to PHP and this might be a stupid question to most of you. I am just hoping someone can explain so I have a better understanding of it.
I am still not understanding how to display something in a table.

The browser only reads html.
PHP is a programing language, interpreted by the server, used to generate html that the browser reads.
That said there are no such thing as PHP tables. Just do a table the normal way. Take a look at the example bellow that uses PHP to create a "dynamic" table. Now imagine that the $animals gets pulled from a database...
Example:
my-table-generator.php
<?php
$animals = array("dog", "cat", "duck");
?>
<table>
<tr>
<?php
foreach($animals as $animal)
{
echo "<td>".$animal."</td>";
}
?>
</tr>
</table>

PHP helps you send dynamic HTML to the browser. The HTML always remain the same regardless of the backend language you are using. So just use regular HTML and use PHP to render it. For instance if you want to display multiple rows of some data coming from the DB, you will utilize a PHP loop to print out the <tr><td></td></tr>
example:
for($i = 0 ; $i < 10 ; $i++){
echo "<tr><td>$i</td></tr>";
}
Probably not a very good example but hopefully it will get the message across.

Related

How do I use PHP code stored in a database and echoed in a new page?

I am a beginner in PHP, so I need a little help.
I have stored some PHP code in a MySQL database (in a table), and now I'm trying to echo in another PHP page (<?PHP echo $result['code'];?>) after making a successful connection with the database and selecting the right table where I stored the code in the code column. But it is not working.
If I store HTML or JavaScript or any code in the database and try to echo, the content is displayed as it was programmed, as you can see in this image:
.
But it doesn't work with PHP. How can I fix it?
I am going to have to do some guessing, and show a very simple example, but something like the following should work.
Add a code_type column to your table with values of html, php, etc.
Make sure that any php code stored in the database has been tested and returns some output (without using <?php tags). For example:
$var1 = 100;
$var2 = 10;
$var3 = 1;
echo "<h1> The equation of ($var1*$var2+$var3) equals</h1>";
echo "<p>".($var1*$var2+$var3)."</p>";
Use the code_type in your data-output script to either evaluate the PHP code or just echo it in all other cases:
<?php
if ($result['code_type'] == 'php') {
eval($result['code']);
} else {
echo $result['code'];
}
?>
I cannot say that I have ever used this, so I can't guarantee anything, but hopefully points you in the right direction.
Important:
It is worth noting that this is not considered good practice, as noted multiple times in the PHP Manual page. The manual itself notes it in several places, but the first comment is on-key:
If eval() is the answer, you're almost certainly asking the wrong
question. -- Rasmus Lerdorf, BDFL of PHP
... You are probably a lot better off parsing the php code before you save it to the database, then you won't have to worry about any of this!

Getting PHP to write clean html

My PHP tends output html in really long, difficult to read html.
If my PHP is written as:
<?php
echo "<li>";
echo "<strong>Hello</strong>";
echo "</li>";
?>
it outputs HTML like this
<li><strong>Hello</strong></li>
which dosnt look that bad, but imagine if thats within a foreach loop which out putted variants of that, all on one line..
Is there a way to get my PHP to output as neatly composed HTML ?
There is: include the whitespace in your output (for example, add \n after each tag).
However, doing that is really an exercise in futility. If you want to view the HTML yourself, get an HTML pretty printer (or use the one included in your browser's developer tools). If it's meant for a browser, the browser doesn't care.
Use a template engine like SMARTY. This will allow you to keep all your html in completely different files than your PHP (it does compile as PHP). This will improve the readability of all of your code. You can then format the html any way you see fit.
You can use the \n to make a line break.
<?php
echo "<li>\n";
echo "<strong>Hello</strong>\n";
echo "</li>\n";
?>
But why use your time on it? Chrome details console will fix it if its because you use the html source as a debug tool.
Whether this is nice or not is subjective, but it works:
<?php
for ($i = 0; $i < 5; $i++)
{
?>
<li><strong>Hello</strong></li>
<?php
}
?>
What I'm trying to get at here is that you can go in and out of PHP mode, so if you have long strands of HTML, you can format them as such, instead of echoing everything.

Using Simple HTML DOM to Scrape?

Simple HTML DOM is basically a php you add to your pages which lets you have simple web scraping. It's good for the most part but I can't figure out the manual as I'm not much of a coder. Are there any sites/guides out there that have any easier help for this? (the one at php.net is a bit too complicated for me at the moment) Is there a better place to ask this kind of question?
The site for it is at: http://simplehtmldom.sourceforge.net/manual.htm
I can scrape stuff that has specific classes like <tr class="group">, but not for stuff that's in between. For example.. This is what I currently use...
$url = 'http://www.test.com';
$html = file_get_html($url);
foreach($html->find('tr[class=group]') as $result)
{
$first = $result->find('td[class=category1]',0);
$second = $result->find('td[class=category2]',0);
echo $first.$second;
}
}
But here is the kind of code I'm trying to scrape.
<table>
<tr class="Group">
<td>
<dl class="Summary">
<dt>Heading 1</dt>
<dd>Cat</dd>
<dd>Bacon</dd>
<dt>Heading 2</dt>
<dd>Narwhal</dd>
<dd>Ice Soap</dd>
</dl>
</td>
</tr>
</table>
I'm trying to extract the content of each <dt> and put it to a variable. Then I'm trying to extract the content of each <dd> and put it to a variable, but nothing I tried works. Here's the best I could find, but it gives me back only the first heading repeatedly rather than going to the second.
foreach($html->find('tr[class=Summary]') as $result2)
{
echo $result2->find('dt',0)->innertext;
}
Thanks to anyone who can help. Sorry if this is not clear or that it's so long. Ideally I'd like to be able to understand these DOM commands more as I'd like to figure this out myself rather than someone here just do it (but I'd appreciate either).
TL;DR: I am trying to understand how to use the commands listed in the manual (url above). The 'manual' isn't easy enough. How do you go about learning this stuff?
I think $result2->find('dt',0) gives you back element 0, which is the first. If you omit that, you should be able to get an array (or nodelist) instead. Something like this:
foreach($html->find('tr[class=Summary]') as $result2)
{
foreach ($result2->find('dt') as $node)
{
echo $node->innertext;
}
}
You don't strictly need the outer for loop, since there's only 1 tr in your document. You could even leave it altogether to find each dt in the document, but for tools like this, I think it's a good thing to be both flexible and strict, so you are prepared for multiple rows, but don't accidentally parse dts from anywhere in the document.

Good coding practice

I am graduating this June, so before that I want to prepare myself for working in the industry :)
My Question:
For example I want to list all the songs in the table using a list box and this is how I implemented it:
playlist.php
<tr id='' >
<td width="" class=""> <font color=#00000 />Select Songs</td>
<td width="" colspan="">
<select size='25'multiple='multiple' id="select_songs" name="playlist_songs[]">
<?php
display_songs_list();
?>
</select></td>
</tr>
and I have a seperate php_functions.php file where I have implemented all the php functions
function display_songs_list(){
$query = "select * from songs order by ID asc";
$result = mysql_query($query);
if(!$result)
echo "<script language = 'javascript'>alert('$result Sorry couldn't connect to the database...');</script>";
else{
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
while($row = mysql_fetch_array($result)){
$ID = $row['ID'];
$title = $row['title'];
$value = $ID.'_'.$title;
echo "<option id=\"$ID\" value=\"$value\">$ID : $title</option>";
}
}
}
}
Is this way of implementation recommended. What else I can do to increace the scalability/maintainability/re-usability. please guide me on this. Is it recommended to follow any industry coding standards, if so what you perfer. Thank you.
Inline style attributes (color=#00000) are deprecated and kill kittens. Learn about CSS.
Tables are discouraged for anything except tabular data (think spreadsheets), use CSS for layout instead.
Hardcoding whitespace with is not desirable either if it doesn't add any meaning, learn to add spacing using CSS.
echoing either HTML or Javascript from the same function is bad. The Javascript alert will cause invalid HTML syntax at the point you're calling the function.
Mixing database calls and HTML so tightly is not good. Look into MVC separation.
Outputting a random, rather meaningless Javascript alert to the user in the middle of a half finished page is bad. You should display a dedicated error page instead. See MVC, which helps you accomplish this.
Mixing single quotes and double quotes for the attributes is inconsistent and makes the code more difficult to read. Stick to one type of quotes instead.
There is no form in your markup shown to submit the selected select options
Take my advice with a grain of salt, but first, you should really separate the code that talks with the database from the code that's given the user errors, they are two separate things. So an idea of how to achieve that in php might be a function that queries the database and returns an associate array with all the results that another function then prints. Also, you should have a more general database class that all your queries go through. The reason this would be preferred is that you can easily switch databases at a later point in time with minimal changes to your code, but if in every function you call mysql_query() it could become more complicated.
Its a reasonably good approach to take for php.
I normally split up my code into an Model/View/Controller type model.
The "controller" is the program which runs when the URL hits the server. It:-
grabs and checks any get/posted variables from the screen.
kicks of any requested actions such as database updates.
kicks of some "model" functions to get the data for the next screen.
formats the next screen using a "view" function or functions.
Note the controller doesn't itself emit any html.
The "model" functions do the database access and apply "business" rules.
The "view" functions emit html tags etc.
Apart from general neatness the big advantage of this is that you processing sequences isn't tied to the order the fields appear on the screen. So it really does make the programs more maintainable.

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.

Categories