Wednesday, March 5, 2008

PAGING WITH PHP

<html>

<head>

<title>Implementing Paging with next and prev</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body>

<?php

include '../library/config.php';

include '../library/opendb.php';


// how many rows to show per page

$rowsPerPage = 20;


// by default we show first page

$pageNum = 1;


// if $_GET['page'] defined, use it as page number

if(isset($_GET['page']))

{

$pageNum = $_GET['page'];

}


// counting the offset

$offset = ($pageNum - 1) * $rowsPerPage;


$query = "SELECT val FROM randoms LIMIT $offset, $rowsPerPage";

$result = mysql_query($query) or die('Error, query failed');


// print the random numbers

while($row = mysql_fetch_array($result))

{

echo $row['val'] . '<br>';

}

echo '<br>';


// how many rows we have in database

$query = "SELECT COUNT(val) AS numrows FROM randoms";

$result = mysql_query($query) or die('Error, query failed');

$row = mysql_fetch_array($result, MYSQL_ASSOC);

$numrows = $row['numrows'];


// how many pages we have when using paging?

$maxPage = ceil($numrows/$rowsPerPage);


// print the link to access each page

$self = $_SERVER['PHP_SELF'];

$nav = '';

for($page = 1; $page <= $maxPage; $page++)

{

if ($page == $pageNum)

{

$nav .= " $page "; // no need to create a link to current page

}

else

{

$nav .= " <a href=\"$self?page=$page\">$page</a> ";

}

}


// creating previous and next link

// plus the link to go straight to

// the first and last page


if ($pageNum > 1)

{

$page = $pageNum - 1;

$prev = " <a href=\"$self?page=$page\">[Prev]</a> ";



$first = " <a href=\"$self?page=1\">[First Page]</a> ";

}

else

{

$prev = '&nbsp;'; // we're on page one, don't print previous link

$first = '&nbsp;'; // nor the first page link

}


if ($pageNum < $maxPage)

{

$page = $pageNum + 1;

$next = " <a href=\"$self?page=$page\">[Next]</a> ";



$last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";

}

else

{

$next = '&nbsp;'; // we're on the last page, don't print next link

$last = '&nbsp;'; // nor the last page link

}


// print the navigation link

echo $first . $prev . $nav . $next . $last;


// and close the database connection

include '../library/closedb.php';

?>

</body>

</html>

PAGING WITH PHP

<html>

<head>

<title>Implementing Paging with next and prev</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>

<body>

<?php

include '../library/config.php';

include '../library/opendb.php';


// how many rows to show per page

$rowsPerPage = 20;


// by default we show first page

$pageNum = 1;


// if $_GET['page'] defined, use it as page number

if(isset($_GET['page']))

{

$pageNum = $_GET['page'];

}


// counting the offset

$offset = ($pageNum - 1) * $rowsPerPage;


$query = "SELECT val FROM randoms LIMIT $offset, $rowsPerPage";

$result = mysql_query($query) or die('Error, query failed');


// print the random numbers

while($row = mysql_fetch_array($result))

{

echo $row['val'] . '<br>';

}

echo '<br>';


// how many rows we have in database

$query = "SELECT COUNT(val) AS numrows FROM randoms";

$result = mysql_query($query) or die('Error, query failed');

$row = mysql_fetch_array($result, MYSQL_ASSOC);

$numrows = $row['numrows'];


// how many pages we have when using paging?

$maxPage = ceil($numrows/$rowsPerPage);


// print the link to access each page

$self = $_SERVER['PHP_SELF'];

$nav = '';

for($page = 1; $page <= $maxPage; $page++)

{

if ($page == $pageNum)

{

$nav .= " $page "; // no need to create a link to current page

}

else

{

$nav .= " <a href=\"$self?page=$page\">$page</a> ";

}

}


// creating previous and next link

// plus the link to go straight to

// the first and last page


if ($pageNum > 1)

{

$page = $pageNum - 1;

$prev = " <a href=\"$self?page=$page\">[Prev]</a> ";



$first = " <a href=\"$self?page=1\">[First Page]</a> ";

}

else

{

$prev = '&nbsp;'; // we're on page one, don't print previous link

$first = '&nbsp;'; // nor the first page link

}


if ($pageNum < $maxPage)

{

$page = $pageNum + 1;

$next = " <a href=\"$self?page=$page\">[Next]</a> ";



$last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";

}

else

{

$next = '&nbsp;'; // we're on the last page, don't print next link

$last = '&nbsp;'; // nor the last page link

}


// print the navigation link

echo $first . $prev . $nav . $next . $last;


// and close the database connection

include '../library/closedb.php';

?>

</body>

</html>

PHP MYSQL SEARCH

//search.htm page

<html>

<body>

Search:

<form method='post' action='search.php'>

<input type='text' name='search' size='25' maxlength='25'>

<input type='Submit' name=' Search ' value='Submit'>

</form>

</body>

</html>

//search.php page


<?php


$host="Host";

$username="Username";

$password="Password";

$db_name="Database Name";

$tbl_name="Table Name";


mysql_connect("$host", "$username", "$password")or die("Cannot connect");

mysql_select_db("$db_name")or die("Cannot select database");


$search=$_POST["search"];


search

$result = mysql_query("SELECT * FROM $tbl_name WHERE name LIKE '%$search%'");


while($r=@mysql_fetch_array($result))

{


//change the names to your columns

$topic=$r["topic"];

$message=$r["message"];

$name=$r["name"];

$date=$r["date"];

$id=$r["id"];



//display the row

echo "<b>$id</b> | <b>$topic</b> by <b>$name</b> at <b>$date</b><br><br>$message";

}

if(!search){

echo "Please enter a search.";

}

else

{

echo "Sorry, there were no searches with the criteria of <b>$search</b>.";

}

?>

Resize image

<?php

$conn = mysql_connect("localhost", "username", "password") or die(mysql_error());

mysql_select_db('test', $conn) or die(mysql_error());

if(@$_FILES['userfile']['tmp_name']){

resize();

$q = "INSERT INTO test VALUES ('', '".$blob_arr['image']."', '".$blob_arr['thumb']."', '".$blob_arr['type']."')";

$aa = mysql_query($q,$conn) or die(mysql_error());


}


function resize(){

global $blob_arr;

$temp_name =$_FILES['userfile']['tmp_name'];

$userfile_name =$_FILES['userfile']['name'];

$userfile_size =$_FILES['userfile']['size'];

$userfile_type =$_FILES['userfile']['type'];


$thumb_width=90;

$thumb_height=90;

$image_width=300;

$image_height=400;


if (!($userfile_type =="image/pjpeg" OR $userfile_type =="image/jpeg" OR $userfile_type=="image/gif" OR $userfile_type=="image/png" OR $userfile_type=="image/x-png")){

die ("You can upload just images in .jpg .jpeg .gif and .png format!<br / >");

}

$data = fread(fopen($temp_name, "rb"), filesize($temp_name));

$src_image = imagecreatefromstring($data);

$width = imagesx($src_image);

$height = imagesy($src_image);

if ($thumb_width && ($width < $height)) {

$thumb_width = ($thumb_height / $height) * $width;

} else {

$thumb_height = ($thumb_width / $width) * $height;

}

if ($image_width && ($width < $height)) {

$image_width = ($image_height / $height) * $width;

} else {

$image_height = ($image_width / $width) * $height;

}

$dest_img = imagecreatetruecolor($thumb_width, $thumb_height);

$i_dest_img = imagecreatetruecolor($image_width, $image_height);

imagecopyresized($dest_img, $src_image,0, 0, 0, 0,$thumb_width, $thumb_height,$width, $height);

imagecopyresized($i_dest_img, $src_image,0, 0, 0, 0,$image_width, $image_height,$width, $height);

ob_start();

if($userfile_type == "image/jpeg" OR $userfile_type == "image/pjpeg"){

imagejpeg($dest_img);

}

if($userfile_type == "image/gif"){

imagegif($dest_img);

}

if($userfile_type == "image/png" OR $userfile_type == "image/x-png"){

imagepng($dest_img);

}

$binaryThumbnail = ob_get_contents();

ob_end_clean();

ob_start();

if($userfile_type == "image/jpeg" OR $userfile_type == "image/pjpeg"){

imagejpeg($i_dest_img);

}

if($userfile_type == "image/gif"){

imagegif($i_dest_img);

}

if($userfile_type == "image/png" OR $userfile_type == "image/x-png"){

imagepng($i_dest_img);

}

$binaryImage = ob_get_contents();

ob_end_clean();

if(!get_magic_quotes_gpc()){

$binaryThumbnail=addslashes($binaryThumbnail);

$binaryImage=addslashes($binaryImage);

}

$blob_arr['image']=$binaryImage;

$blob_arr['thumb']=$binaryThumbnail;

$blob_arr['type']=$userfile_type;

}

if(@$_POST['submit']){

$Rs = mysql_query("SELECT * FROM test WHERE id = '".mysql_insert_id()."'", $conn) or die(mysql_error());

$row_Rs = mysql_fetch_assoc($Rs);

header( "Content-type: ".$row_Rs['filetype']."");

echo $row_Rs['thumb'];

}else{

?>

<form name="form1" method="post" enctype="multipart/form-data" action="<? echo @$PHP_SELF; ?>">

<input id="userfile" name="userfile" type="file" />

<input type="submit" name="submit" value="Submit" />

</form>

<?

}

?>

Monday, March 3, 2008

MySQL Joins

Thus far we have only been getting data from one table at a time. This is fine for simple takes, but in most real world MySQL usage you will often need to get data from multiple tables in a single query.

The act of joining in MySQL refers to smashing two or more tables into a single table. This means everything you have learned so far can be applied after you've created this new, joined table.

MySQL Join Table Setup

We like to show examples and code before we explain anything in detail, so here is how you would combine two tables into one using MySQL. The two tables we will be using relate to a families eating habits.

family Table:

Position Age











Dad 41
Mom 45
Daughter 17
Dog
food Table:Meal Position











Steak Dad
Salad Mom
Spinach Soup
Tacos Dad
The important thing to note here is that the column Position contains information that can tie these two tables together. In the "family" table, the Position column contains all the members of the family and their respective ages. In the "food" table the Position column contains the family member who enjoys that dish.

It's only through a shared column relationship such as this that tables can be joined together, so remember this when creating tables you wish to have interact with each other.

MySQL Join Simple Example

Let's imagine that we wanted to SELECT all the dishes that were liked by a family member. If you remember from the previous lesson, this is a situation when we need to use the WHERE clause. We want to SELECT all the dishes WHERE a family member likes it.

We will be performing a generic join of these two tables using the Position column from each table as the connector.

Note : This example assumes you have created the MySQL tables "food" and "family". If you do not have either of them created, you can either create them using our MySQL Create Table lesson or do it manually yourself.

PHP and MySQL Code:

<?php

// Make a MySQL Connection

// Construct our join query

$query = "SELECT family.Position, food.Meal ".

"FROM family, food ".

"WHERE family.Position = food.Position ";

$result = mysql_query($query) or die(mysql_error());

// Print out the contents of each row into a table

while($row = mysql_fetch_array($result))

{

echo $row['Position']. " - ". $row['Meal']; echo "<br />";

}

?>



The statement "WHERE family.Position = food.Position" will restrict the results to the rows where the Position exists in both the "family" and "food" tables.


Display:


Dad - Steak

Mom - Salad

Dad - Tacos

Those are the results of our PHP script. Let's analyze the tables to make sure we agree with these results.


Compare the Tables:



Position Age
















Dad 41
Mom 45
Daughter 17
Dog

Meal Position











Steak Dad
Salad Mom
Spinach Soup
Tacos Dad
Our results show that there were three meals that were liked by family members. And by manually perusing the tables it looks like there were indeed three meals liked by family members.

thank's to tizag.com

Ajax

To create this important Ajax object, you are going to have to use a special programming technique known as "try and catch". Basically it attempts to "try" a piece of code and if that piece causes an error it "catches" the error and keeps going. Normally when an error occurs the code will stop running, however, the "catch" eats up the error and lets the code continue.


In the following code we are going to "try" three different ways to make a new XMLHttpRequest object. Every time we fail and get an error, we will catch the error and try the next a different command.


Note: If our "try" is successful then the "catch" code will not be run because it is only used when there is an error.


order.html Javacsript Code:



<html>


<body>

<script language="javascript" type="text/javascript">

<!-- //Browser Support Code function ajaxFunction(){

var ajaxRequest; // The variable that makes Ajax possible!

try{ // Opera 8.0+, Firefox, Safari

ajaxRequest = new XMLHttpRequest();

}

catch (e){ // Internet Explorer Browsers

try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

}

catch (e) {

try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

}

catch (e)
{ // Something went wrong

alert("Your browser broke!");

return false; }

}

}

}

//-->

</script>



<form name='myForm'>

Name: <input type='text' name='username' /> <br />

Time: <input type='text' name='time' />

</form>


</body>


</html>



In the above Javascript code, we try three times to make our XMLHttpRequest object. Our first attempt:



  • ajaxRequest = new XMLHttpRequest();


is for the Opera 8.0+, Firefox and Safari browsers. If that fails we try two more times to make the correct object for an Internet Explorer browser with:



  • ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

  • ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); >


If that doesn't work, then they are using a very outdated browser that doesn't support XMLHttpRequest , which also means it doesn't support Ajax.


Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server.


Ajax - That Browser Specific Code is Confusing


The code in this lesson was quite complex, but the good thing is that you can just copy and paste this code and don't really have to understand it. I bet you wish I would have told you that at the beginning of the lesson!


The next lesson will teach you how to use your XMLHttpRequest object (which is currently stored in ajaxRequest variable) to communicate with the server.

Simple 2 Column CSS

This tutorial will teach you some basic CSS layout stuff, you will be able to create a simple 2 column layout (with a header) that you can use on pretty much any website. It won't be anything fancy, but it will be solid!


Alright, let's get started. When im doing CSS work, I often switch back and forth between the HTML and CSS as I go along, so you will be switching back and forth between your CSS file and your HTML file often.


Before we even start coding, let's visualize how it should look in our browser, first we want to make sure that the layout is centered, in internet explorer AND firefox, it should have a header, 1 column for content, and another for navigation, easy enough!


So let's start with some CSS



body {


margin : 0px auto ;


text-align : center ;


background-color : #f59751; /* This is set to light orange, change this to the color you want as your site's background. */


}


.end {


clear : both ;


}



Alright, let's break this code down.



body {


margin : 0px auto ;



The body { part means that we are editing the body of the HTML (The <body> tag) so it effects our whole page, the margin: 0px auto; is what makes our site centered, in firefox.



text-align : center ;



This is what makes it centered, in IE (Internet Explorer). Don't worry, not all of our text is going to be centered, because we just change it back to normal when we make our container!



background-color : #f59751; /* This is set to a light orange, change this to the color you want as your site's background. */


}



This is just what the global background color of our site is going to be, I have set it to a light grey, just change the hex color to whatever you want and the site's background will change.


Now we need to start our HTML document, just the nasty beginning stuff.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns= "http://www.w3.org/1999/xhtml" xml: lang = "en" >


<head>


<meta http-equiv = "content-type" content = "text/html; charset=utf-8" / >


<title> TutorialCode.com - CSS 2 Column Layout </title>


<style type = "text/css" media = "screen" title = "Main StyleSheet" > @import "style.css"; </style>


</head>


<body>



This just start off our HTML document, remember to always code by the standards (It's not mandatory though). This will set your document type to transitional, as well as set your character set, we also put our title (which you can change) and include our stylesheet. Then we end our head section, and start our body.


 



#container {


width : 750px;


text-align : left ;


margin : 0px auto ;


background-color : #de7c3d; /* This is a darker orange */


}



Now we finally create our container, I'll explain a part of it.



text-align : left ;



This is where we set our text back to normal, since everything will be contained within this container, all text will be written on the left, but since we have our body set to center, the whole template will be centered.


Back to our HTML for a quick add! Right underneath of your <body> tag, add this -



<div id = "container" >



This starts our container div for our layout, for the most part your CSS file is accessed using the <div> tag, you will learn more about it after.



#header {


width : 730px;


margin-left : 10px;


background-color : #f7771c; /* Pure Orange */


height : 115px;


}


    #header h1 {


font-size : 20px;


font-family : georgia;


color : #3975bd; /* A blue */


padding : 20px;


}



This is where we create our header, our header is just going to be a background color, with some text in it. I'll break down some of the parts of it.



margin : 10px;


background-color : #f7771c; /* Pure Orange */


height : 115px;



This margin makes it so that everything is spaced 10px away from the header, on all sides. We then set our background color and then we make our header 115px in height.



#header h1 {



Now, we want to put some text in our header, and let's say we want to use the <h1> tag to display it, the default <h1> tag is very ugly, so we style it. As you can see, we leave the #header part in front of the h1, that is because we only want <h1> tags to be styled this way, in our header. Just by reading the rest of it, you can understand it!


Now let's put our header in action, with our HTML, directly under the <div id="container"> tag would this code -



<div id = "header" >


<h1> Simple 2 Column Layout </h1>


</div>



This starts our header, and writes something using our <h1> tag that we specified.


Now let's create our content area.



#content {


width : 520px;


margin-left : 10px;


margin-right : 10px;


margin-bottom : 10px;


float : left ;


background-color : #eee; /* Light Grey */


font-family : tahoma;


font-size : 11px;


color : #666666; /* Dark Grey */


padding : 5px;


}



This is quite a big portion of CSS, it's all pretty easy though. You have seen everything in here except for -



float : left ;



This is how we get 2 divs (our content and navigation) right next to eachother. The rest is easy enough to understand, now let's make our navigation.



#navigation {


width : 190px;


float : left ;


background-color : #eee;


font-family : tahoma;


font-size : 11px;


color #666666;


}


    #navigation li {


padding-left : 8px;


margin : 0px;


list-style : none ;


}


        #navigation li a {


text-decoration : none ;


color : #49a8ec;


font-family : tahoma;


font-size : 11px;


}



Well, that's even MORE CSS. First we create our navigation column in the same was as our content column, then we get to the #navigation li part, this is where we define the <li> tag, it's an easy way to display links in a navigation, we give them a padding of 8, so all our links are 8px away from the left side also the



list-style : none ;



code means that there wont be anything beside each li element,the default is those ugly dots. Now that doesn't take care of our link styling though.



text-decoration : none ;


color : #49a8ec;



That part of the code makes our links have no underline, and makes them a nice blue. Then we just set the font.


Now we just finish up our HTML and were done! We now add our content div -



<div id = "content" >


filler text......


</div>



You may want to go to lipsum.org to generate some filler text so you know what your site will look like with text in it, that's what I did at least!



<div id = "navigation" >

<li> <a href = "#" > Link Test </a> </li>

<li> <a href = "#" > Link Test </a> </li>

<li> <a href = "#" > This is a long Link Test </a> </li>

<li> <a href = "#" > Link Test </a> </li>

<li> <a href = "#" > Link Test </a> </li>

<li> <a href = "#" > Link Test </a> </li>

</div>



This is where we put our navigation into the HTML, we start our navigation div, then for each link we start a new <li> element, add in our link, and just continue onto the next one. This makes for very clean navigation code, and is easy to read, then we close our navigation div, almost done!



<div class = "end" > </div>


</div>


</body>


</html>



The <div class="end"></div> part is so that our container background, is pulled as far as our content box goes, if we don't put that our container background will only go as far as the header, and it looks weird! Then we close up our container, end our body and html tags and were done!


If you have any questions, just leave a comment! You will be answered quickly, or if you have anything you want to say just feel free to leave a comment.


Download the source files here

PHP Basics - Beginner Tips

Alright, just thought that instead of leaving you guys in the dust with no new tutorials, I could write a small, simple (but good) tutorial on some of the basics of PHP. If you look through all the tutorials on this site as a beginner to PHP you may not understand a lot of it, and need a back to basics explanation of everything, so with that in mind this tutorial will cover -

1. Conditions (if statements)
2. Loops
3. Basic Functions

Beginner to intermediates can benefit from this tutorial, you may just pick up a tip or 2!

Alright, before we start learning anything from the actual list above, I think it would be beneficial to learn how PHP actually works. You can't learn the basics of PHP without knowing the base of PHP first.

PHP is a server side scripting language, this means that it is executed on the server, and the results are sent back to the browser as HTML.

When testing out your PHP applications, you can't just create the file, save it and open it locally on your own computer, you either need to install Apache, PHP and MySQL (if your using a database, which you should). All that is pretty complicated, so an easier solution is to get webhosting. You can find webhosting for as low as $1 (which isn't exactly the best, but ok for testing). Once you get webhosting, you can just use an FTP program (easy to use) and upload your files onto your website, most webhosts, actually I would bet 97% of webhosts have PHP installed, so it should be easy to find one. Also, just a side note when you create PHP applications if your file has PHP in it, you need to save it with the .php extension so the browser knows to execute it as PHP.

Now, probably the most basic (and most over-done) PHP example is

< ? php

echo 'Hello World!';

?>

Alright, if your completely new to PHP this may need some explaining. The ).

Next we use an echo, this is how we output text to the browser, echo 'Text Here'; is the proper format, notice the ending ; on the line, most lines of PHP require you to input that, there are exceptions that we will cover later though.

PHP Conditionals (if statements)

Probably in every PHP script, you will use conditionals, from if statements to switch statements they are everywhere, let's get right into it and start you off with a simple if statement, probably the most used conditional.

< ? php

if (1 == 1) {
echo '1 really does equal 1!';
}

?>

Alright, this is probably the easiest if statement you will ever see, it doesn't even have an else part to it. If you can't understand this (which I hope you can) then I will explain it, all it's doing is saying if 1 is equal (using 2 equal signs is how you define equal to) to 1 then continue, and all we do is echo out a simple statement. You can do anything though, you don't have to echo. Then we end the statement. Now let's use the same thing but add on an else, so if it doesn't equal one we have somewhere to go.

< ? php

if (1 == 1) {
echo '1 really does equal 1!';
} else {
echo 'Aww, 1 doesn\'t equal 1.';
}

?>

As you can see, all we did was add on } else { then add another echo statement. Pretty straight forward, but let's say we are using variables, we can make another tiny bit more complicated example.

< ? php

$number = 1;
$answer = 2;
if ($number == $answer) {
echo '1 really does equal 1!';
} else {
echo 'Aww, 1 doesn\'t equal 1.';
}

?>

We use variables in this example, we have a number variable ($number) and an answer variable ($answer), we define static data to these variables, meaning they don't change, but that will be different when you start getting into MySQL and such.

Then instead of comparing 2 numbers in our if statement, we compare our 2 variables. Pretty much the exact same thing, except now our variables both contain different numbers so our output will then be Aww, 1 doesn't equal 1. because our 2 variables did not equal each other, so we go to our else statement.

This is just the basics of if statements, but this is also just a basic PHP tutorial. If you want to learn more about if statements check out any of the tutorials on this site, chances are they use if statements in them.

Now let's check out switch conditionals, these are in theory the same as if statements except they allow you to have a lot of different answers to them. Here, I will show you a simple example first -

< ? php

$var = 'Cows';
switch ($var) {
case 'Dogs';
echo 'You chose dogs!';
break;
case 'Cats';
echo 'You chose cats!';
break;
case 'Cows';
echo 'You chose cows!';
break;
case 'Birds';
echo 'You chose birds';
break;
default:
echo 'You didn\'t choose any animals!';
break;
}

?>

At first glance, this may look a bit overwhelming, but break it into parts in your mind. Let's assume that we have a form where a person chooses a favorite animal, and then there chose is saved into a variable called $var. From there we output an answer depending on what they choose. First we define that we are starting a switch, we want to then put in what we want to check, then we have each case, a case is what we are trying to match with our switch, if our switch and one of our cases match we continue on with that case, if not we keep checking through them. If our switch matches none of our cases, then we have a default, from there we just put out any old answer that you want your user to see.

PHP Loops

Loops are great for executing sections of code over and over again to do the same thing, I know when I first started in PHP I though, "what's the point of that?" well when you get more and more advanced it will become a lot more useful. We will discuss, for loops and while loops. First, we will start with for loops, let's make a for loop that outputs the numbers 1 to 10, each number on a new line.

< ? php

for ($n = 1; $n <= 10; $n++) {
echo $n.'
'
;
}

?>

For being such a small piece of code, this can be actually quite confusing, but if you understand it, you will think "Doh, that was easy". Ok, first you use the for loop function, now this is where you do all your variable defining, the first part is where you define the value of your first variable, then from there you make your condition saying, if that number is smaller then or equal to 10, continue, and then if it is smaller then or equal to 10 we add one onto our variable ($n++ means add one to that variable). Then we execute a piece of code, now the next time we go back, but our $n variable equals 2, and it does this until $n is equal to 10.

Now for the while loop, this one is a bit easier to understand, and is used more often (well I use it more often) it is used VERY often when dealing with MySQL, people use it to extract data from there MySQL results, we won't be covering that in this tutorial though, for my example I will just be showing you an example of how to do the same thing we did with our for loop

< ? php

$n = 1;

while ($n <= 10) {
echo $n.'
'
;
$n++;
}
?>

This will do the same thing as our for loop, except with more code and not as compact, usually a while loop will be used more when working with databases. As you can see, we define our $n variable outside of our loop, then we just do a easy to understand loop, and at the end of our code we add 1 onto our $n variable.

Basic PHP Functions

In the last section of our tutorial we will cover some basic functions in PHP that every user should know, and most likely will use.

These functions will deal with strings, first we will start with a function that will count all the characters in a string (this includes spaces).

< ? php

$string = 'The Big City';
$len = strlen($string);
echo $len;

?>

In this example, we define a variable, in this variable we define the string we want to use, next we use our function, we assign the output of this function for better coding practices, we use the strlen() function, all it does is output a number based on how many characters are in the string, then we echo out our variable, that will give us our answer, in this example our answer is 12.

Next, we will use a function that turns our string into an array, this has many usages, in this example we will use the same string that we just used before.

< ? php

$string = 'The Big City';
$array = explode(" ", $string);
echo $array[2];

?>

Ok, again we make a variable, and define our string in our variable, then we use the explode() function and assign it to a different variable, now the explode function takes 2 arguments, a separator and a string. We say that our separator is a space, (thats the blank space) and that our string, is the variable that we defined before. Now after doing that, we need to echo out what part of the string that we want. When you use the explode function, it turns our string into an array. When you make an array, the first item in the array is defined as [0], the second item is [1] and so on, so if we wanted to access the word City, which is the 3rd item we would want to echo out $array[2].

That is all for now, if you have something you want to learn more about in PHP, just leave a comment and I will add it onto this tutorial!

Thanks for visiting TutorialCode.com