tutorial redone - mixing HTML and PHP
Posted: Wed Jan 21, 2004 4:14 am
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
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
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.
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
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
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.
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.......
is used in most PHP scripts that you write, this is all often replaced by
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
?>
the include command means if the file is not found then PHP will do its upmost to continue without the file
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).
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
as the script will fail if there are no values in the array
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.
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 ' ' 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
the correct way can be found here
however the easier way of doing this would be by substituting the 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
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
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!
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
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
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
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';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
</table>
</body>
</html>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>Code: Select all
</table>Code: Select all
<?php
$host = "localhost";
$user = "yourname";
$password = "yourpassword";
$DBname = "yourdatabase";
$tablename = "login";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);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);Code: Select all
include ('database_connections.php')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')
?>Code: Select all
$query = "SELECT * FROM login";
// select the database
mysql_select_db($DBname);
// query the database
$result = mysql_query($query);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);Code: Select all
<tr bgcolor=#9BD7FF>
<td width=35%>$dataїusername]</td>
<td width=40%>$dataїemail]</td>
<td width=25%>$dataїaccess_level]</td>
</tr>";- 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>' '</td>
<td>above and below are errors</td>
<td>' '</td>
</tr>
</table>Code: Select all
print "escaping characters is done "Like this".";
// notice quotes inside each other, the \ symbol will escape and then go back to...............<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 these values
Code: Select all
$data[username]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>";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
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>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