Guide An Introduction to PHP

UndeadDragon

Super Moderator
Reaction score
447
php.gif

An introduction to PHP

What is PHP?
PHP (PHP: Hypertext Pre-processor) is a server-side scripting language, which executes before the server returns the HTML. (PHP cannot be viewed by looking in the source). PHP files can be saved as: “.php, .php3, .php4, .php5 or .phtml”. An important feature in PHP is its ability to connect with many different databases.

How can I get PHP?
PHP is a free, open source software, which can be downloaded here and it requires a server, the most popular is Apache, which can be downloaded here. Most web hosts support PHP, so if you have an account they provide a method to test your scripts without having to install PHP.

Get started with PHP
All PHP scripts are enclosed by either the <?php ... ?> tags or the shorthand tags, which are <? ... ?>. PHP scripts are often contained within the HTML tags, so the syntax would be like:

PHP:
<html>
<head>
<title>A PHP Test</title>
</head>

<body>
<?php
echo("Ahoy World!");
//A simple PHP script
?>
</body>
</html>

The echo(“Ahoy World!”); part of the PHP script simply displays the text “Ahoy World”. All PHP functions must end with a semi-colon (;). The text after // is ignored, as that is a single line comment. Comments which span multiple lines are enclosed by /* and */.

PHP Variables
Variables are an important part of PHP. They are used to store information (or arrays of information). All variables in PHP must begin with the dollar sign ($). If anyone is moving from JavaScript to PHP, they should know that in PHP a variable does not have to be declared before its use, as it is automatically declared when in use. There are a few rules for naming variables:
1. A variable name must start with a letter or underscore.
2. A variable name may only contain letters or numbers.
3. A variable name cannot contain spaces.

Some examples:

PHP:
<?php
$string = "Test"; //Valid
$_string = "Test"; //Valid
$1string = "Test"; //Invalid
$a string = "Test"; //Invalid
$a_string = "Test"; //Valid
?>

Variables can be displayed in an echo() function by either directly displaying it:

PHP:
<?php
$string = "Ahoy World";
echo($string);
?>

...Or by using a concatenation operator. A concatenation operator (.) basically joins 2 strings together. You can use this to join multiple variables together, or to join a variable and some static text. Example:

PHP:
<?php
$string = "Ahoy World";
echo($string . "2");
?>

Variables can also be in arrays and they can be referred to by their index. There are two ways to create arrays. The most commonly used way is to assign each value manually:

PHP:
<?php
$array[0] = 0;
$array[1] = 1;
?>

The other way is to declare all array values in one function:
PHP:
<?php
$array = array(0,1); //Does exactly the same as the first example
?>

You can retrieve the number of elements in an array using the function count($arrayName). Example:

PHP:
<?php
$int[1] = 1;
$int[2] = 2;
$int[3] = 3;
$count = count($int);
echo($count); //Prints 3
?>

If...Else
If...Else is an important feature in all languages. The syntax is as follows:

If (condition)
{
//This code is ran if the condition is equal to true.
}

The condition must have a comparison operator to be able to work. The operators are as follows:

== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

An example of an “if/else” statement:

PHP:
<?php
$year = date(Y); //Gets the year
if ($year == 2000)
   {
   echo("Happy Millennium!");
   }
else
   {
   echo("It is year... " . $year);
   }
?>

While loop
The while loop runs a piece of code whilst a condition is true. The conditions in the while loop use the same comparison operators as if/else. The following example uses the while loop to display the numbers 1 to 100.

PHP:
<?php
$i = 1;
while($i <= 100)
{
echo($i);
$i++; //Increment. Increases $i by 1
}
?>

$_GET and $_POST
If you want to get some information from a form then $_GET and $_POST are your best friend. Which one to use? It depends on your form, the method to be exact. If your form’s method is GET, the information from the form will be passed to the page in the “action” through the URL. It will make the URL look something like:

[noparse]http://www.example.com/mail.php?name=George&[email protected]&message=Ahoy[/noparse]

The information could then be retried on the next page by using $_GET. Example:

PHP:
<?php
$name = $_GET['name']; //Gets "George"
$email = $_GET['email']; //Gets "[email protected]"
$message = $_GET['message']; //Gets "Ahoy"
?>

Because $_GET displays all the submitted information in the URL, it is obviously not the best choice for validating a username and password, so that is where $_POST comes in. $_POST works in exactly the same way, apart from it doesn’t show the information in the URL, so it is much more secure.

Let’s look at a simple contact form as an example:

contactForm.htm
PHP:
<html>
<head>
<title>Contact Form</title>
</head>

<body>
<form method="post" action="mail.php">
Name: <input type="text" name="name"/>
Email: <input type="text" name="email" />
Message: <textarea name="message"></textarea>
</body>
</html>

mail.php
PHP:
<?php
$to = "[email protected]";
$subject = "Contact Form";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$headers = "From:" . $name;
mail( $to,$subject,$message,$headers );
?>

Note: To be able to use the mail() function, you must first configure your php.ini, if using a local server. Click here to see how.

Functions
You can create your own functions in PHP which can make it quicker to do certain tasks which would otherwise need lots of code. You create your own function using the syntax:

function funcName(parameters)
{
//Do stuff here
}

The function name may only contain letters, numbers and underscores and may only start with a letter or underscore. The code which should be executed when the function is called is contained within the curly brackets.

Example:

PHP:
<?php
function multiply($number,$multiplier)
{
$result = $number * $multiplier;
return $result;
}
$answer = multiply(10,100);
echo($answer); //prints 1000
?>

Introducing MySQL
There are different databases that PHP also supports, but I am MySQL tends to be the preferred and most widely used database. PHP can execute queries, which allow it to input or retrieve data to/from a database. Before a query is executed, you must connect to the database. Example:

PHP:
<?php
$host = "localhost";
$username = "root";
$password = "abc123";
$database = "users";

mysql_connect($host,$username,$password);
mysql_select_db($database);
?>

Once you have created a connection and selected a database, you can execute some queries on it. Firstly, imagine that we have a database which has this structure:

Code:
Table: characters
id | FirstName | LastName   |
1 | Homer      | Simpson    |
2 | Marge      | Simpson    |
3 | Bart       | Simpson    |
4 | Lisa       | Simpson    |
5 | Maggie     | Simpson    |

Here is an example query on this table, I will explain it after:

PHP:
$query = "SELECT * FROM characters WHERE id='3'";
$result = mysql_query($query);

"SELECT *" means select all results. "FROM characters" means from the table characters "WHERE id='3'" means where the number in column "id" is equal to 3. So, the whole query means:

Select all results from the table "characters" where the row id is equal to 3.

Now, to get the actual data from the rows. The query has found 1 row which matches the query. The row’s data is id:3, FirstName:Bart, LastName: Simpson. To get each piece of data we will use a while loop with a special condition: while($row = mysql_fetch_array($result)). What this does is get all the data from the query (mysql_fetch_array($result)) and assigns it to $row. You can now access the data inside the while loop by using row as an array, where the index is equal t the column name. Example:

PHP:
$host = "localhost";
$username = "root";
$password = "abc123";
$database = "db";

mysql_connect($host,$username,$password);
mysql_select_db($database);

$query = "SELECT * FROM characters WHERE id='3'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
   {
   $first_name = $row['FirstName'];
   $last_name = $row['LastName'];
   }
echo($first_name . last_name); //Prints "Bart Simpson"

Adding MySQL tables using PHP
If you want to add tables without having to run a query directly through MySQL you can do so through PHP. An example function:

PHP:
<?php
$host = "localhost";
$username = "root";
$password = "abc123";
$database = "user_db";

mysql_connect($host,$username,$password);
mysql_select_db($database);

$query = "CREATE TABLE users (
id int,
username varchar(32),
password varchar(32),
email varchar(255) )";
$result = mysql_query($query);
echo("Table Created");
?>

This query will create a table on the "user_db" database which contains the columns: Id, Username, Password and Email. Id has the "int" type, because it will always be an integer and the username, password and email columns have the type varchar(Number in here represents the max length of the string) which means that it holds a string.

If you wish to learn more about SQL and the different queries, you can check out w3school’s SQL tutorial here.

If you wish to know more about PHP functions you can go to php.net/function name. For example: http://php.net/date() will take you to the date() documentation.

Thanks for reading my tutorial. If anyone wants anything added, please ask.
 

ReVolver

Mega Super Ultra Cool Member
Reaction score
609
Excellent tutorial, but you must mention in mail.php that you must edit your php.ini in order for it to send mail. the url tags in the $_GET section need to be fixed. You should add a mysql section to show how to add tables into your DB.
 

UndeadDragon

Super Moderator
Reaction score
447
Excellent tutorial, but you must mention in mail.php that you must edit your php.ini in order for it to send mail. the url tags in the $_GET section need to be fixed. You should add a mysql section to show how to add tables into your DB.

Thanks for the feedback. Everything has been added.
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
*votes for sticky*
Very nice. +rep on it.
 

UndeadDragon

Super Moderator
Reaction score
447
Thanks for the kind comments :)

Anyone notcied any mistakes? I probably have made 1 or 2, I usually do :p
 

UndeadDragon

Super Moderator
Reaction score
447
You might want to mention something about count() and explode()

I will try and mention count() but I don't really see why I would include explode() in a beginners tutorial.
 

Samuraid

Advisor
Reaction score
81
You might also want to mention how one can look up functions in the PHP manual simply by going to:

php.net/<function-name>
 

UndeadDragon

Super Moderator
Reaction score
447
You might also want to mention how one can look up functions in the PHP manual simply by going to:

php.net/<function-name>

Thanks. Added.
 

Slapshot136

Divide et impera
Reaction score
471
for some reason the links dont work for me, other then that it looks good, maybe adding some brief description of what some common php uses are though would improve it
 

UndeadDragon

Super Moderator
Reaction score
447
Links should work now. I don't know what the hell Microsoft word did to my URL tags :p
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
for some reason the links dont work for me, other then that it looks good, maybe adding some brief description of what some common php uses are though would improve it

Common uses? Anything really, the most common is making dynamic content pages though.
 

Blackveiled

Formerly, Ban-Lord
Reaction score
157
for some reason the links dont work for me, other then that it looks good, maybe adding some brief description of what some common php uses are though would improve it

Using PHP could mean the difference between a crappy and a decent website. If you don't use PHP, you will have to do a lot more work than necessary also, but it also depends what you are doing too.
 

codemonkey

Code monkey not crazy, just proud.
Reaction score
66
Using PHP could mean the difference between a crappy and a decent website. If you don't use PHP, you will have to do a lot more work than necessary also, but it also depends what you are doing too.

For static sites PHP isn't necessary.
 

DDRtists

ɹoʇɐɹǝpoɯ ɹǝdns
Reaction score
415
For static sites PHP isn't necessary.

Indeed, however, now a days static sites rarely go far. People want change, new stuff, new things. You have to give people a reason to come back, something static sites don't do.
 

TFlan

I could change this in my User CP.
Reaction score
64
Indeed, however, now a days static sites rarely go far. People want change, new stuff, new things. You have to give people a reason to come back, something static sites don't do.

Aka, live updates like Facebook's News Feeds. Google has even stated themselves that they need more real-time applications on their site, and that they are falling behind in that category.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
    +1
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though
  • Ghan Ghan:
    Heard Houston got hit pretty bad by storms last night. Hope all is well with TH.
  • The Helper The Helper:
    Power back on finally - all is good here no damage
    +2
  • V-SNES V-SNES:
    Happy Friday!
    +1
  • The Helper The Helper:
    New recipe is another summer dessert Berry and Peach Cheesecake - https://www.thehelper.net/threads/recipe-berry-and-peach-cheesecake.194169/

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top