How to display tabular data in PHP? - php

I am coming from Asp.net world, where everything is so modular that it creates headaches and nausea sometimes and you forget what you were actually doing.
Here in PHP I was trying to study how to display tabular data, and the solution was very simple but that looked very hasty, because if I write lots of code then it will become haywire.
So my question is what standard should I follow to work with repeating data, if there is any? Please guide me to some quality material to study because I tried but did not find anything. I have studied this link.
[Edit]
The way asp.net render tabular data is by using GridView. here you just create an instance of the GridView class and send it the data retrieved from the database and remain job is done behind the scene without messing the C# or VB code with html or writing the same logic again and again. I mean it is nice example of code resuability and I want to utilize something similar here in php to write the repeating code once and then inherit it if I want it somewhere else.

I myself have migrated from ASP.NET to php and one word of advice is forget what ever you learnt in ASP.net as ASP.net abstracts a lot of thing in web development to a point you forget that you are working with basic html/jscript and http. but again, this is just a personal opinion.
Ragarding your question on how to display a table and populate it with data. Have a look at this example. Here
<?php
$people = array(
array('Tom', '16'),
array('John', '21'),
array('Kate', '19'),
array('Luke', '25')
)
?>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Name</td><td>Age</td>
</tr>
<?php foreach($people as $person){ ?>
<tr>
<td><?php echo $person[0]; ?></td>
<td><?php echo $person[1]; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
I create a 2d array contain data about People and their age. Due to simplicity sake, im using a hard coded array and not retrieving data from a database.
I then use a while loop to loop through the data in the array and for each tuple, I add a <tr> in the table. This is something like a repeater in ASP.NET
DEMO
Just noticed you want a modularized version. Here is an example:
index.php
<?php
include('inc.datasource.php');
$people = DataSource::getUsers();
?>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Name</td><td>Age</td>
</tr>
<!-- Render rows with data -->
<?php foreach($people as $person){ ?>
<tr>
<td><?php echo $person[0]; ?></td>
<td><?php echo $person[1]; ?></td>
</tr>
<?php } ?>
<!-- End render rows with data -->
</table>
</body>
</html>
inc.database.php
<?php
class DataSource{
public static function getUsers(){
//Connect to database
//Retrieve user data
//Return user data
//Simulating the above steps for simplicity sake
$people = array(
array('Tom', '16'),
array('John', '21'),
array('Kate', '19'),
array('Luke', '25')
);
return $people;
}
}
?>
If you want to completly seperate your php from your html. I suggest you use one of the php mvc frameworks. I personally like using Laravel and CodeIgniter

Related

How can I run PHP code in an specific html section

I have a section in my .html page where I want to run some PHP code, which reads data from a database and 'echoes' the table filled up with that information. I kinda did it object-oriented so I'm trying to keep that along the project.
I have this exact function or method in the Class (Class Servicio):
public static function listaServicios(){
$servicios = array();
$query = "";
$db = Database::getInstance();
$query = "SELECT descripcion, precio FROM servicio";
$resultado = $db->conn()->query($query);
foreach($resultado as $item){
$servicio = new Servicio();
$servicio->setDescripcion($item['descripcion']);
$servicio->setPrecio($item['precio']);
array_push($servicios,$servicio);
}
return $servicios;
}
As you can see, the function just returns an array filled up with as many objects as rows there is in the table. The PHP page would call this method, and then print the table with the selected data inside (there is no problem with this).
The thing is how can I print it in the specific section (div with id='datos') previously mentioned, which simply is:
<section class="principal">
<div id="datos">
</div>
</section>
I kinda of have an idea but I really don't know to implement it. Maybe using a document.ready function in jQuery calling the PHP code? I would really like to use this language even if it is a very tiny function in order to learn.
You can use jquery's load function to load content via a remote file into the div. But you will need to update your listaServicios to return html instead of the array.
jquery:
$(document).ready(function(){
$('#datos').load('phpfile.php');
});
phpfile.php
<?php
$serv = new Servicio();
echo $serv->listaServicios();
?>
Correct answer to your question depends on the interface of your future application you want to reach.
If you want some kind of SPA, then you should make AJAX-requests using JavaScript (jQuery or something else) and create a separate controller to response with data.
But I think in your particular case you can do everything on server side.
First of all you should add new method to your class, name f.e. render:
public static function render(){
$services = static::listaServicios();
include 'path/to/your/template.php';
}
Then inside your template.php write next:
<section class="principal">
<div id="datos">
<?php
foreach($services as $service) {
// echo your $service here as you wish
}
?>
</div>
</section>
So after calling render() PHP will render that part of template.
To access the properties of Servicio is better you construct your table in php:
<?php $servicios = Servicio::listaServicios(); ?>
<section class="principal">
<div id="datos">
<table style="width:100%">
<tr>
<th>Descripcion</th>
<th>Precio</th>
</tr>
<?php foreach ($servicios as $servicio): ?>
<tr>
<td><?= $servicio->getDescripcion() ?></td>
<td><?= $servicio->getPrecio() ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</section>

PHP + HTML in MySQL echo

This will in this case echo multiple authors, release dates, and covers for a book on a single page.
My question is: How do I make it look nice with a table, and my CSS file? I just can't get it right, kinda almost made it work once, but it showed just the one book and then started on a new row, and I want at least 4 books/row, and the borders were completely off.
Really silly question I know, and I've tried googling and experimenting but I'm having serious trouble making it really work.
Also, if I want to echo a variable ($genre) in a link-text, say
Home > Books > CurrentGenreVariable($genre)
how'd I do that neatly? I need a slight kick-start, that's all I think.
Thanks in advance.
You follow the generic looping patterns. I presume you're doing this with a while() loop?
<table>
<?php while ($row = FETCH_THE_DATA): ?>
<tr>
<td><?php echo $row['author']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['cover']; ?></td>
</tr>
<?php endwhile; ?>
</table>

How to use DOM object for Current PHP page

In my php page I am getting a list of cities and events dynamically from a database. Then I'm passing this sql data to jquery to render a table with the data. Sample table created by jquery could be like:
<tr>
<td id='cityMumbai'>Mumabai</td>
<td id='program1Start>11/11/11</td>
<td id='program2Start'>11/15/11</td>
<tr>
Now I've come to know that DOM can be used to manipulate table structure in php.
I saw various reference, and found it is being used to create a new page. Means the created paged is saved physically.
Possible Pseudo Code:
{
<span id="eventRows">
<? $object = new DOMDocument;//it should pick this specific instance ?>
<? while($row = mysql_fetch_array($rProgList,MYSQL_ASSOC)):?>
<? // write code to check if current cityname exitst?
$td = $object->getElementById($row['cityname']);
if(!$td.exists): ?>
<tr><td id="<? echo $row['cityname'];?>"><? echo $row['cityname'];?></td></tr>
<? else : ?>
<?
//code to insert only event information in the current city object
$td.append("dfkjsdflkjasdhflkjsfh");
?>
<? endif; ?>
<? endwhile; ?>
</span>
}
Can I use DOM in PHP to modify the page output, only... replacing the task jquery is doing using PHP. Not to modify a physical copy of it.

sql, php, html table question

I want to grab data from a mysql database by using php. The data looks something like this:
apple 3
orange 2
banana 4
I want to take the data and put it in a html table and use css to make it look pretty, but I dont want to deal with it inside <?php ?>
After I grab the
$result = mysql_query("SELECT * FROM Table");
can I reference the result variable outside the <? php ?> tags?
No. PHP can only be done in <?php ... ?> or <?= ... ?>. Use a template engine such as Smarty if you want substitution in this manner.
in short, no you cant, it is a php variable (technically a resource in this case) so you have to parse it through the php engine, which requires the php tags
echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fruit'].'</td><td>'.$row['id'].'</td></tr>';
}
echo '</table>';
Short answer is no. HTML cannot deal with dynamic content.
If you want to cut down the amount of echo statements within your code you can store the html within a given variable and then make reference to it.
I find it better to do the following:
<table>
<?php foreach($result as $row): ?>
<tr>
<td><?php echo $row['fruit']?></td>
<td><?php echo $row['id']?></td>
</tr>
<?php endforeach; ?>
</table>
This provides clarity and minimizes concatenation.

PHP logical coding style

I have to modify some parts of a large PHP application. The different parts were written, of course, by different people (mostly interns). After looking through the code, I found that there were 2 styles of coding used by the other developers:
The 'PHP is the glue of the Internet' style, mixing html and php, ex.:
[snip]
<tr class="ds_subsubhead_2">
<td colspan="21" align="left"> A <select name="nb_linge" onChange="MM_jumpMenu('parent',this,0)" style="vertical-align:middle"> <option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','9999') ?>" <? if($messagesParPage == '9999') { ?>selected="selected"<? } ?>>Tous</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','25') ?>" <? if($messagesParPage =='25') { ?>selected="selected"<? } ?>>25</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','50') ?>" <? if($messagesParPage =='50') { ?>selected="selected"<? } ?>>50</option>
<option value="<?=get('index.php',$orgurl,'nb_ligne=','22','23','75') ?>" <? if($messagesParPage =='75') { ?>selected="selected"<? } ?>>75</option>
[snip] or
<td <? if((isset($_GET['t1']))&&($_GET['t2']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t3']))&&($_GET['t4']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
<td <? if((isset($_GET['t5']))&&($_GET['t6']!='ALL')) { ?>bgcolor="#0099FF"<? } ?>></td>
[snip] or even
<script type="text/javascript" src="<?=$_SESSION["path"]?>lib/js/ajax.js"></script>
[snip]
... and the more procedural way, ex.:
[snip]
$output .= '<td valign="top"><form name="form5" method="GET" action=""><select name="m" onchange="this.form.submit()">';
if ( empty($_GET['p']) ) $output .= '<option value=" ">All</option>';
else $output .= '<option value='.$_GET['m'].'>'.$_GET['m'].'</option>';
$query = "SELECT DISTINCT maoie FROM ".$BD."site";
$res = mysql_query($query);
while ( $row = mysql_fetch_assoc($res) ) {
if( !empty($row['maoie']) ) $output .= '<option value="'.$row['maoie'].'">'.$row['maoie'].'</option>';
}
$output .= '</select></form></td>';
$output .= add_more_stuff();
echo $output;
Now, I'm not completely sure that this is a more procedural way to do things, but at least it is different from the previous one. Which one, do you think, is generally better?
I, personally, dont't like 'the glue of the Internet' style.
I would ditch both and code the PHP away from any presentation-layer specific HTML. Otherwise things get very nasty, very quickly for anything bigger than 'Hello World' :)
You are shooting yourself in the foot if you want to modify the code later. I would try and kill off this problem by porting to a proper CMS/Abstract presentation.
Neither look good. I wouldn't want to maintain code in either style. save time later by spending time now cleaning it up properly.
Even something as basic as moving your HTML into externally loaded format strings and running them through sprintf() or similar might be better than the current situation. And you say you have a mix of these coding styles !?!
good luck to you sir!
Both styles should be relegated to the tomb of dynamic internet growing pains. Take a peek through some open source PHP projects to see a good, maintainable coding style in action. Things like http://sourceforge.net/projects/wikipedia MediaWiki show a good mix of HTML-In-Source and separation (although it is not perfect IMHO)
There is a third option: templates. Templates are more readable than glue or random emission of ascii vomit. I just tend to use HEREDOCd strings and str_replace, thus:
$template = <<<TEMPLATE
<html>
<head>
<title>{TITLE}</title>
</head>
<body>
<div id='nav'>{NAV}</div>
<div id='content'>{CONTENT}</div>
</body>
TEMPLATE;
$data = array (
"{TITLE}" => "Page title example",
"{NAV}" => buildNav(),
"{CONTENT}" => buildContent());
str_replace(array_keys($data),array_values($data), $template);
I tend to go for something in the middle. If I'm calling fifteen different functions to generate a select <option>, why not just have one function that does everything and creates the complete markup?
Something like this (completely made up example):
<select>
<?php
foreach (database_query() as $row)
echo gen_select($row)
?>
</select>
and somewhere else
function gen_select($row) {
// do something horrifically complicated with the data (creating some variables to make the output easier to follow
return "<option class=\"$class\">$text</option>";
}
I personally work on a CMS that has the latter version, and I am having a very hard time reading it.
2ndly, model/controller code within view's is a great Italian dish.
Both are horrible (that's the real weakness of PHP in my opinion), but at least the first looks readable.
Problems will eventually arise once conditions (is the request POST? is the data valid?) are added, and it will lead invariably to the dreaded second kind of coding. Try to decouple view and logic: str_replacing is way better than building a string by concatenating one gazillion small pieces.
No offence, but both style is from the late '90-s.
You should seriously consider refactor the system and use a template engine to separate at least the PHP and the HTML code.
Even better if you can separate the "business logic" and the "display logic" part.
I think HTML and PHP should be seperated as much as possible. It makes the whole code easier to read and creates a clear structure. That means for me that PHP should not output HTML, since you can use HTML to do that part...
So I'd also prefer the last example, but with one difference: I think using the bracket-style mixed into HTML makes it very hard to read the code. The if...endif style is the better alternative I think. Also printing HTML with PHP seems unlogic.
I'd do it this way:
<td valign="top"><form name="form5" method="GET" action=""><select name="m" onchange="this.form.submit()">;
<? if ( empty($_GET['p']) ): ?>
<option value=" ">All</option>
<? else: ?>
<option value="<?=$_GET['m']?>"><?=$_GET['m']?</option>
<? endif; ?>
<?
$query = "SELECT DISTINCT maoie FROM ".$BD."site";
$res = mysql_query($query);
while ( $row = mysql_fetch_assoc($res) ):
?>
<? if( !empty($row['maoie']) ): ?>
<option value="<?=$row['maoie']?>"><?=$row['maoie']?></option>
<? endif; ?>
<? endwhile; ?>
</select></form></td>
<? echo add_more_stuff(); ?>
At least this is a bit more logic. Nevertheless things like database interaction should be excluded to somewhere else in your web application. If you seperate the data and the design of your page it gets much clearer.
Nevertheless I think using PHP as a template language is totally fine as long as you only use some replacement variables and simple if-statements.

Categories