Can I separate data and layout better? (PHP, mysql, html)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Nineor
Forum Newbie
Posts: 3
Joined: Wed Jul 29, 2015 7:02 am
Location: UK

Can I separate data and layout better? (PHP, mysql, html)

Post by Nineor »

Sorry if I am very much a newbie asking this :oops: , but:

- How do I in general keep data and design apart?
- Can I keep my databaseAccess file more "clean", only obtaining the data, and do the work of viewing/layout in my other file?

As you can see I am using variables to try and make the databaseAccess file more reusable,
but as soon as I need to extract data from the table, I am ruining that as I am locked at using a given amount of columns (and I currently have HTML code inside it, which seems messy to me).

Any suggestions for a cleaner design?

Part of "Books.php":

Code: Select all


 <?php 
			 	$table='books';
				$db='test';
				$row1='title';
				$row2='author';
				include 'databaseAccess.php'; 

			 ?>

databaseAccess.php:

Code: Select all

<?php

define("SERVER", "localhost");
define ("BRUKERNAVN", "....");
define ("PASSORD", "..."); 
define ("DATABASENAVN", $db);

$db_handle=@mysql_connect(SERVER, BRUKERNAVN, PASSORD); 

if (! $db_handle)
	die('Klarte ikke koble til ');

$returverdi=@mysql_select_db(DATABASENAVN);  
if (! $returverdi)
{
	@mysql_close($db_handle);
	die ('klarte ikke velge db');
}

/* Queries */

$query="select * from " .$table;

$resultat=@mysql_query(mysql_real_escape_string($query));

echo "<table>";
echo "<th> Title </th> <th> Author </th>";
while($rad=@mysql_fetch_array($resultat))
{
	echo "<tr><td>" . $rad[$row1] . "</td><td> " . $rad[$row2] . "</td></tr>";
}

echo "</table>";

@mysql_free_result($resultat); 
@mysql_close($db_handle);

?>


User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Can I separate data and layout better? (PHP, mysql, html

Post by Celauran »

Try to avoid includes. Look at the front controller pattern, namespacing, and MVC. All of these will help you achieve a much cleaner separation of concerns. Look at how modern PHP frameworks structure their applications.
Nineor
Forum Newbie
Posts: 3
Joined: Wed Jul 29, 2015 7:02 am
Location: UK

Re: Can I separate data and layout better? (PHP, mysql, html

Post by Nineor »

Thanks :)
Was never any good at MVC (and have never heard of the others), but it is of course better that a messy code :D

if this weather keeps up I should have enough time to check it out :p
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Can I separate data and layout better? (PHP, mysql, html

Post by Christopher »

Lots of newbie code here. A few comments:

- Don't use die(). Instead, check for error conditions, get error messages and set the error status. The give the user a nice error page.
- Don't suppress errors with @.
- Keep defines to a minimum (or do them in classes). The point of constants is that you cannot accidentally reassign them. So don't set variables and then use them as values for the defines -- that defeats the protection.
- Don't use the mysql extension. Use mysqli or PDO.

The code below, as ugly as it is, is what can be called the Domain Model -- often just called the Model. One way to think of the Domain is that it is the code that is not dealing with getting the Request from the user, or generating the Response back to the user. It mostly is the code that deals with datasources, sub-systems, etc.

Put this code into two classes: one for the database connection and another that access the books table. Pass the database connection object to the books object's constructor.

Code: Select all

			 	$table='books';
				$db='test';
				$row1='title';
				$row2='author';
				include 'databaseAccess.php'; 

define("SERVER", "localhost");
define ("BRUKERNAVN", "....");
define ("PASSORD", "..."); 
define ("DATABASENAVN", $db);

$db_handle=@mysql_connect(SERVER, BRUKERNAVN, PASSORD); 

if (! $db_handle)
	die('Klarte ikke koble til ');

$returverdi=@mysql_select_db(DATABASENAVN);  
if (! $returverdi)
{
	@mysql_close($db_handle);
	die ('klarte ikke velge db');
}

/* Queries */

$query="select * from " .$table;

$resultat=@mysql_query(mysql_real_escape_string($query));
This is your Presentation code, which is the Response back to the user. Separate it into its own file. And because we don't want any domain code in here, pass it an object of your Model class above that it can fetch the rows with.

Code: Select all

echo "<table>";
echo "<th> Title </th> <th> Author </th>";
while($rad = $books->fetch())
{
	echo "<tr><td>" . $rad[$row1] . "</td><td> " . $rad[$row2] . "</td></tr>";
}

echo "</table>";
Don't do this stuff. PHP has to close everything when the script ends, and does it much more efficiently that you can. Only in cases where you know what your are doing should you close/free.

Code: Select all

@mysql_free_result($resultat); 
@mysql_close($db_handle);
(#10850)
Nineor
Forum Newbie
Posts: 3
Joined: Wed Jul 29, 2015 7:02 am
Location: UK

Re: Can I separate data and layout better? (PHP, mysql, html

Post by Nineor »

ok thanks

Yow know the scary part?
All of that database code, apart from me sending the variables to use with with the DB + the html for a table,
is what my programming teacher taught us to do :p
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Can I separate data and layout better? (PHP, mysql, html

Post by Christopher »

Nineor wrote:Yow know the scary part?
All of that database code, apart from me sending the variables to use with with the DB + the html for a table,
is what my programming teacher taught us to do :p
This is horrible. Your teacher should at minimum have started by passing the connection information to a function. Then converted that function to the constructor for a connection class and added supporting methods. That would actually teach some useful PHP skills.
(#10850)
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: Can I separate data and layout better? (PHP, mysql, html

Post by yacahuma »

After making hundreds of php sites, my advise is:

1. Forget about symphony, cake, bla, bla bla, framework 1,2,3,99. Every month someone want to create a new framework. Is like watching fashion come and go. PHP is just so simple that learning someone else solution to a non problem is ridiculous.
2. create a database library for every table(or by object). Ex

Code: Select all

    class DBUser
    {
        function insert(){}
        function delete(){}
        function find($filter){}
     }
3. Keep your html clean. Create dynamic elements outside html so that they dont get clutter.

Code: Select all

<?
$db = DBUser($dbconnection);
$users = $db->find($filter);
$table ='<table>';
foreach ($users as $user)
{
    $table .= '<tr><td>'.  $user->name. '</td></tr>';
}
$table .= '</table>'; 

?> 
<html>
  Hello <?=$user?>

  Your table is <?=$table?>

  <form>
  </form>
</html>


This work for me 100% of the time. Dont matter if the job is big or small. Is easy for my to update my html and my php code. There will ALWAYS be a bit of php inserted in html. You could try to do everything in ajax, and you get more separation. For me it just depends on what I try to accomplished.


I hate every single framework out there. In more than 20 years I have seen them come and go. Why make something complex out of something simple? I have no idea. Every framework have bug. I only have to deal with php bugs and thats it. I did created my own library to create html widgets(table,select,input) but they are very small and there is really nothing new to learn to use them. All these frameworks require major investment in time and energy.
Post Reply