Page 1 of 1

tutorial redone - mixing HTML and PHP

Posted: Wed Jan 21, 2004 4:14 am
by malcolmboston
ok i thought i'd write out some tutorials because i notice alot of 'advanced posts' are being bumped off for easy and simple problems which could be easily researched just by clicking on search

ok here we go

i am not writing out these codes to try and teach, im going be trying to point out the simple commands in PHP that are extremely easy to learn and invaluable also listing common pitfalls.

please feel free to make adjustments to the code, because i have not tried to make it perfect, just 'newb-friendly'

ok so what is the purpose of this script?
- turn 1000+ lines of HTML into 30-50 lines of PHP,
- mix PHP and HTML together WITHOUT errors
- Show how a common App could be created

ok you'll need this first

Code: Select all

CREATE TABLE login (
  username varchar(25) NOT NULL default '',
  email varchar(40) NOT NULL default '',
  access_level varchar(20) NOT NULL default 'Member'
) TYPE=MyISAM COMMENT='actual login form used for logging in';
This is MySQL syntax, if you do not know what MySQL is then let me explain.
MySQL is an open-source database and is commonly used in PHP development as a ways and means of producing dynamic web-sites, Login systems etc. While not as powerful as other databases such as PostgreSQL, MySQL integrates with PHP seamlessly and has plenty of facilities for the less demanding user.
MySQL is also extremely fast you can find a full explanation of MySQL here

Insert the above piece of code into PHPMyAdmin ( a very good MySQL GUI), without it you will not see the end results and its just easier if i provide the code

ok heres the whole PHP script, ill break it down in a minute

Code: Select all

<html>
<head>
<title> looping rows demo </title>
</head>
<body>
<table width=500 border=0 cellspacing=0 cellpadding=0>
  <tr bgcolor=#009999>
<td><strong>Username</strong></td>
<td><strong>E-Mail Address</strong></td>
<td><strong>Status</strong></td>
</tr>
<?php
// database variables for connections 
$host = "localhost"; 
$user = "yourname"; 
$password = "yourpassword"; 
$DBname = "yourdatabase"; 
$tablename = "login"; 
//connection variables completed 
// establishing connections 
$link = mysql_connect ($host, $user, $password);
//connection established 
//the query defined 
$query = "SELECT * FROM login"; 
// select the database 
mysql_select_db($DBname); 
// query the database 
$result = mysql_query($query); 
$data = mysql_fetch_array($result, MYSQL_ASSOC);
print "
<tr bgcolor=#9BD7FF>
    <td width=35%>$data[username]</td>
    <td width=40%>$data[email]</td>
    <td width=25%>$data[access_level]</td>
  </tr>";
while ($row = mysql_fetch_assoc($result))
print "
<tr bgcolor=#9BD7FF>
    <td>$row[username]</td>
    <td>$row[email]</td>
    <td>$row[access_level]</td>
  </tr>";
?>

Code: Select all

&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
ok so what is this all doing i hear you ask, well basically its just displaying all the information in a database, simple as that, however this could be easily adapted for use in a CMS (Content Management System). lets break it down.

Code: Select all

&lt;html&gt;
&lt;head&gt;
&lt;title&gt; looping rows demo &lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table width=500 border=0 cellspacing=0 cellpadding=0&gt;
  &lt;tr bgcolor=#009999&gt;
&lt;td&gt;&lt;strong&gt;Username&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;E-Mail Address&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Status&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
ok, as the more observational of you may of noticed, this isnt PHP at all and is not held within the PHP tags, why have i done this you ask? well, if you go all the way to the bottom of the script you will notice the tag

Code: Select all

&lt;/table&gt;
this ensures that even if there are no results in the database to return then the table will still be rendered properly and without errors, i have also created the first <td> and <tr> so that i have the user end-user has a way of knowing at first glance what the columns hold

Code: Select all

<?php
$host = "localhost"; 
$user = "yourname"; 
$password = "yourpassword"; 
$DBname = "yourdatabase"; 
$tablename = "login";
ok, now notice the tag <?php ,that tells the PHP parser that PHP is coming and to parse is accordingly, just as HTML uses the <html> tag, however <?php can be replaced with <? with no consequences
this bit of code is used to define the connection variables, its not mandatory to use this but does make it easier for bigger projects as a value only has to be changed at one spot and not at various places around the page, this is purely done by preference but you will generally see all experienced coders doing this, so it is better to get in the habit now.

Code: Select all

$link = mysql_connect ($host, $user, $password);
this is making a connection to the database, notice the order of the variables, any other order would cause an error connecting to the database, this is a very important script as it defines what database to use for the future of the script (in most circumstances, as you can have more than 1 query to different databases).

Ok, if you are a regular to these forums then you will of noticed that all of the above php.......

Code: Select all

$host = 'localhost'; 
$user = 'yourname'; 
$password = 'yourpassword'; 
$DBname = 'yourdatabase'; 
$tablename = 'login';
$link = mysql_connect ($host, $user, $password);
is used in most PHP scripts that you write, this is all often replaced by

Code: Select all

include ('database_connections.php')
you would then put all of that code into the new file and it should work exactly the same, however there is a major upside to doing this; imagine a site that has 1000's of pages and al use the same connection information, and then your host tells you you have to change your database name, quite rightly you are not going to be a happy chappy right? wrong, doing it this way means you only have to change one file to make the changes site-wide and not having to do each page one-by-one. There are 2 ways you could actually do this with the include() command or with the require() command

Code: Select all

<?php
include ('database_connections.php')
?>
the include command means if the file is not found then PHP will do its upmost to continue without the file

Code: Select all

<?php
require ('database_connections.php')
?>
whereas require means exactly what it says, if the file isnt found PHP will stop in its tracks and throw a fatal exception (not nice).

Code: Select all

$query = "SELECT * FROM login"; 
// select the database 
mysql_select_db($DBname); 
// query the database 
$result = mysql_query($query);
ok now we're at the meat of the code, where all the data is retrieved.
notice the line of code, $query, what it is doing is retrieving all the information relevant to our query, so in this case, select everything from the table called login, however notice how there is a $var created by that piece of code, this means that $query is equal to whatever the value of the query is, we do this because we will need to use this later to create arrays and such.
mysql_select_db is a standard field and is just telling the query where to actually find the field named login.

ok, $result = mysql_query, ok this is where its all happening, this piece of code creates an array, if you dont know what arrays are go here, the subject is too large for me to cover, creating an array is absolutely vital to the rest of this script, also you can test if the query has returned anything by using

Code: Select all

mysql_affected_rows()

as the script will fail if there are no values in the array

Code: Select all

$data = mysql_fetch_array($result, MYSQL_ASSOC);
now because data in an array cannot be 'directly printed' we need to do something with it, that is what that line is for, read the actual code it is obvious what it is doing, notice also that another var is created with the result, MYSQL_ASSOC finds all the relevant information from your query set and stores them in the array for later retrieval and is invaluable in this circmustance.

Code: Select all

&lt;tr bgcolor=#9BD7FF&gt;
    &lt;td width=35%&gt;$data&#1111;username]&lt;/td&gt;
    &lt;td width=40%&gt;$data&#1111;email]&lt;/td&gt;
    &lt;td width=25%&gt;$data&#1111;access_level]&lt;/td&gt;
  &lt;/tr&gt;";
as you can see again, this is simple HTML, however there is one major difference you should take into account with this HTML and the HTML we made earlier, This html is actually within PHP and therefore must conform to PHP's syntax system, for example, us web-designer know what an invaluable piece of code '&nbsp;' is in HTML, it creates a non-breaking space and is therefore invaluable for the more design-driven brains amongst us, however as we know, PHP's "command close" syntax is ; and therefore using the nbsp; tag would seriously screw up your site and would throw up fatal exceptions everywhere, so there are two ways around conflicting syntax
- change you syntax
- escape from PHP and then go back into it

let me explain the latter more closely, when i say escape php and tehn go back into it i dont mean close php (?>) and then go back into it (<?php) in that sense i will show you an example of what i mean

Code: Select all

<?php
<table width="100%">
// error above
<tr>
<td>'&nbsp;'</td>
<td>above and below are errors</td>
<td>'&nbsp;'</td>
</tr>
</table>
the correct way can be found here

Code: Select all

print "escaping characters is done "Like this".";
// notice quotes inside each other, the \ symbol will escape and then go back to
however the easier way of doing this would be by substituting the &nbsp; with something else such as.............
...............<spacer> this would be find as it uses no syntax that PHP has reserved

ok we're coming to the back-end of our tutorial now, so what have we done so far?
- established a connection to our database using variables for ease of use
- ran a query to retrieve the data we want
- created an array
- mixed HTML with PHP
now for the remaining pieces of code

Code: Select all

print " 
<tr bgcolor#9BD7FF> 
<td width=35%>$data[username]</td> 
<td width=40%>$data[email]</td> 
<td width=25%>$data[access_level]</td> 
</tr>";
notice this print statement, this will print out the first value in the array (it will not repeat it) you must do this other wise the repeat will miss out the first row of data, but noticed how ive tidied up the code so if there are no values in the database then my table wont look all screwed up
notice these values

Code: Select all

$data[username]
remember when we created the data array? well now all of the values can be retrieved easily, say you had a field in the table called showme, you could use $data[showme] to print it to the screen, this is very simple but it is a common pitfall to newcomers as arrays often seem daunting to newcomers however perseverance is the key here, ok so hopefully you get the idea from this line of code, go on try it out now!

Code: Select all

while ($row = mysql_fetch_assoc($result)) 
print " 
<tr bgcolor=#9BD7FF> 
<td>$row[username]</td> 
<td>$row[email]</td> 
<td>$row[access_level]</td> 
</tr>";
ok heres our loop statement taht could potentially save us 100's or 1000's lines of HTML, and as you can see its only a few lines!!! ok this is quite a simple control structure
basically the command is saying "while you are fetching the new results and turned them into a $row variable print out a standard table row and insert the data into it accordingly"

what this will do is everytime it finds a result in the array it will print out a row and it will all look neat and tidy :D
as you become more and more able with PHP you will begin to use various commands such as else, if, else/if, while etc etc these are all control structure and should be viewed here
now for our last piece of code

Code: Select all

?> 
</table>
</body>
</html>
notice how we have closed up all of our php and printed a standard end table tag, this means that no matter what the query finds it will always print the </table> tag as PHP has nothing to do with its existence, aslo we have closed out </body> and </html> tags just for good measure

ok well that concludes this weeks tutorial, i am aware of cookies being a nightmare for beginners so i am planning on writing a tutorial on that subject soon (and yes i was also stumped at cookies)

If you have any problem go see my friend herehere
please feel free to annotate and to ask questions

Hope this helps someone out

and good luck with PHP everyone

Posted: Wed Jan 21, 2004 5:56 am
by malcolmboston
move to tutorials?

Posted: Wed Jan 21, 2004 7:18 am
by McGruff
I wish I could teach people to STOP mixing html & php, at least not until they get to the presentation layer. It's like looking at all the bits left after a squirrel's been run over by a truck.

Posted: Wed Jan 21, 2004 7:47 am
by patrikG
McGruff wrote:I wish I could teach people to STOP mixing html & php, at least not until they get to the presentation layer. It's like looking at all the bits left after a squirrel's been run over by a truck.
I totally agree. For more complex applications mixing presentation and logic makes the code and thus the application nigh unmaintainable.
Plus it apparently also slows the PHP-parsing down.

Although sometimes unavoidable, personally I regard mixing HTML with PHP as bad practise.

Posted: Wed Jan 21, 2004 10:28 am
by redmonkey
I wouldn't consider this to be a helpful tutorial.

Given the title, the subject matter is presumably using PHP to output HTML, which I feel is one of the first tasks any newbie creatign PHP web scripts should look into. However, requiring the user to first create a database before they even start is something I feel is way beyond the scope of the intended audience of your tutorial.

I should also point out that although you have the user create a database, you never actually put any data into it, so your whole code is working with an empty database? Although you mention testing to check if the query returned any results, you don't included any such checking within your main code example.

You also neglected to pick up on the previous error I described in your code, so again, your code doesn't work.

My personal conclusion is that you are spending too much time talking about the database side of things and not enough time talking about generating HTML from within PHP.

You should consider using standard variables/arrays for your data and using a simple for loop for your HTML construction, this I feel would be more suited for and understandable by your intended audience.