Overclock.net - Overclocking.net
     
 
Home Gallery Reviews Blogs Register Today's Posts Mark Forums Read Members List


Go Back   Overclock.net - Overclocking.net > Overclock.net Forum > FAQs

 
 
LinkBack Thread Tools
Old 09-19-06   #1 (permalink)
Programmer
 
xxmonkey321xx's Avatar
 
amd nvidia

Join Date: May 2006
Location: Gilbert, AZ
Posts: 319

Rep: 24 xxmonkey321xx is acknowledged by some
Unique Rep: 7
FAQs Submitted: 1
Hardware Reviews: 7
Trader Rating: 2
Default Info: PHP Tutorial Part 1

PHP Tutorial


Welcome to the basic PHP tutorial. You will be learning the following items:
  • Opening/Closing Tags
  • Comments (//, #, and /* */)
  • Variables
  • Echo
  • If/elseif/else
  • $_POST and $_GET
  • Switch
  • Function
  • Arrays
  • Basic MySQL connectivity
  • Include

You will need:
  • Apache HTTP Server, Installed with PHP working
  • MySQL Installed (only if you want to learn how to connect to it)
  • Patience
  • Caffine

Ok, here we go...

Tags surround EVERY PHP script. The tags are <?php for opening, and ?> for closing.

An example:

PHP Code:
<?php

Script here

?>

Comments



It is possible to add comments to scripts, such as your name and a copyright notice, as so:


PHP Code:
<?php
########################
# This is a comment    #
# And catches your eye #
########################

#This is a comment along with everything else on this line

//This is a comment along with everything else on this line.

/* This is a comment along with everything else between the asterisks and slashes */

This line is not a comment

?>
Variables

Let's start with Variables, since they are rather basic and easy to learn.

A few examples of variables:


PHP Code:
<?php

$var 
"hello";
$var2 "world";
$var3 " ";

//NOTICE that each line has a semicolon after it!! You much have a semicolon after EACH AND EVERY separate command.

//Lets combine these variables:

$combined $var $var3 $var2;

//If we were to echo $combined, it would look like "hello world" (without quotes). The periods signify combining.

?>

Variables can be names anything, they just have to start with a $. So $asdkskla is a variable, $hello is a variable and so on.

Echoing

Let's move on to echo.

Echo is a very simple print, spitting out whatever you tell it to.

For example:


PHP Code:
<?php

$hello world 
"Hello World"//THIS WOULD MAKE AN ERROR!!! There is a space in the variable name, which is not allowed.

$hello_world "Hello World";

$number 42//No quotes needed since this is a single number(no spaces)

$number2 $number//Therefore $number2 is the same as whatever $number is

$html "<a href="http://www.overclock.net">Awesome Site</a>";

//So let's echo, shall we?

echo "Hello World!"//Echoes what is in quotes, in this case "Hello World!"

echo $hello_world//Echoes variable $hello_world, which is set to "Hello World!"

echo $number//Will echo variable $number, which is set to 42

echo $number $number2//Will echo 4242 nice both $number and $number2 are set to 42

echo $html// Would echo HTML code which the browser will interpret, and turn into a link in this case.

?>

If/IfElse/Else

You can setup if/else command rather easy. These are handy if you want to check what is input against hat you have in your database, along with some other uses.

A basic if/else command looks like this:


PHP Code:
<?php

if ($variable == $other_var) {

// Code to execute

}
elseif(
$vaiable == $another_var) {

// Code to execute

}
else {

// Code to execute if both if and ifelse(s) all fail. (Last-resort sort of thing)

};
?>

So let's say we have a variable, $input, and we want to check it for age (it's a number). You can make it as a cheap password to get into a section of your site, but this is not recommended.


PHP Code:
<?php

$input 
"42";

if (
$input == 42) {

echo 
"The number is correct! Blah blah...";

}
else{

echo 
"The number is incorrect!";

};

?>

Elseif's are rarely used, since normally you can sum it all up in one if statement.



$_POST and $_GET

POST and GET retrieve information either from forms or from the link itself.

POST gets info from forms, such as username and password. Suppose you had a simple HTML form like so:


Code:
<html>
<head><title>Form</title></head>
<body>

<form name=form method=POST action=script.php>
Username: <input type=text name=username><br>
Password: <input type=password name=pass><br>
<input type=submit value="Login!">
</form>

</body>
</html>

You MUST name the input fields to get info from them.

So, to retrieve the data in that form, you would use $_POST as shown:

PHP Code:
<?php

$username 
$_POST['username']; //you must include the single quotes! the text in the single quotes is the name of your form's input.
$password $_POST['pass'];

echo 
$username// Would echo whatever was in the username field
echo $password// Would echo whatever was in the password field

?>

$_GET is slightly different. It comes in handy when you are using the switch command, which I will go over next.

For example, lets take an example URL:

Code:
http://www.overclock.net/showtopic.php?t=1337
t=1337 is a variable stored (out in the open) in the URL. This can be grabbed by programs and tells them what to do or what to look for, or some other things.


Say you have a PHP program that looks like this:


PHP Code:
<?php

if (isset($_GET['act'])) {

$var $_GET['act'];
echo 
$var//echoes whatever is stored in http://www.example.com/script.php?act=[what is stored here]
}
else{

echo 
"No variable present in 'act'"

};
?>

open this script up and you should get "No variable present in 'act'" on the screen.

Now go to your script like so:

Code:
name.php?act=test
Now it should echo "test".

Like I said before this comes in handy with switch, which you will learn in a second!

****


OK, coffee break.. or whatever, just let you brain rest for a second, to absorb all the wonderful code! Continue whenever you are ready!

****


Switch(s)


A switch is generally a fancy if/else. They come in handy for GET variables. An example of a good usage for switch is:


PHP Code:
<?php

switch(@$_GET['act']) {

case 
"login";

//Login code

break; //REQUIRED at the end of every CASE, not default!




case "logout";

//Logout code, skips over login code since act is set to logout.

break;



default:

//What happens by default if $_GET is unset or is set to something that there is no case command.

};

?>

Don't forget the @ sign, it helps to ward off errors due to strange programming glitches.



Fun with Functions

Functions come in handy if you do a certain thing a lot, like append something to the end of a variable or filename.

You can make a function and call to it at any point after it has been created.

An Example:


PHP Code:
<?php

function FUCNTIONNAME(optional_var1,optional_var2){

//Code

};

FUNCTIONNAME(var,var);
?>

Note that both FUNCTIONNAMEs are all capitals, since PHP is very case sensitive. $t is not the same as $T, as functionname is not the same as FUNCTIONNAME.


A Better example, to append "lmao" to the net of a string:


[PHP<?

function lmao($string) {

echo $string . "lmao";

};

lmao("Look as this, "); //Echoes Look at this, lmao

?> [/PHP]


You can also use a function to append random characters to a filename, using arrays.



Arrays

Arrays store information. Whether it is a little information or a lot, you can use arrays.

Some examples of arrays are:


PHP Code:
<?php

$example 
= array("This""is""an""example");

echo 
$example[0]; //Echoes "This" (no quotes)


/* Example with different entries with names... */

$example2 = array("word" => "Hello""number" => "42""decimal" => ".7777");

echo 
"{$example2[word]}, the number is {$example2[number]}" $example2[decimal]; // Echoes "Hello, the number is 42.7777" (no quotes)

?>

The Curly Brackets ({ and }) are there to tell PHP that you are accessing a variable, so it does not have a conniption when it sees some random brackets ([ and ]).



Basic MySQL connectivity

To connect to a MySQL database you need an address, a username, a password, and a database to connect to. Let's say that for this example, the host(or address) is localhost, the username is root, and the password is toor, though this may not reflect you current settings (or mine, so don't try it).

So, lets set these values as variables, and connect to MySQL!


PHP Code:
<?php

$host 
"localhost";
$user "root";
$pass "toor";
$db "test";

// Now let's connect!

mysql_connect($host$user$pass) or die ("Could not connect to MySQL database!"); //This means if the connection fails with will echo what is in die()

// Ok, now we are connected! Let's select a database

mysql_select_db($db) or die("Could not connect to database!");

//Now we are in the database "test"! We can run queries(ask for information) for the tables in the database!
//I like to do it like this:

$sql "SELECT col FROM table"//This will select the column "col" from table "table" when executed. Lets say that there is one row in this column, with an entry of "Hello World" (old, I know..)

$result mysql_query($sql) or die("Could not execute query!");

echo 
$result//Echoes Hello World

?>
But what if there is more than one row in the column? Here is how you echo them all(simply):


PHP Code:
<?php

$host 
"localhost";
$user "root";
$pass "toor";
$db "test";

mysql_connect($host$user$pass) or die ("Could not connect to MySQL database!");

mysql_select_db($db) or die("Could not connect to database!");

$sql "SELECT * FROM table";

$result mysql_query($sql) or die("Could not execute query!");

//Now for the fun part..

while($row mysql_fetch_array($resultMYSQL_ASSOC)){

echo 
"{$row[col]} <br>" //Would echo each value in column "col" on a new line

};
?>


Includes

Including file is good to hide MySQL connection info and other connection info.

An example for MySQL is this: say you have the connection info in <basedir>/db/db.inc, and you want to get to it..

PHP Code:
<?php

include("db/db.inc"); // Adds the info in db/db.inc into the current file, just like you had typed it in

//connect to MySQL, blah blah... not it has the connection info.

mysql_connect($host$user$pass) or die ("Could not connect to MySQL database!");

?>
It can also be helpful to store files outside of the viewable web server, such as outside of HTDOCS holder or WWW folder, depending on what you use. You can include these too like:


PHP Code:
<?php
// Lets say you are in /Apache2/htdocs/program/code/ and you want to get to something in /apache2/path/to/file.extention ...
include("../../../path/to/file.extention");

// Ok, so the first ../ brings you back to the program directory, the second brings you to htdocs, and the third brings you outside of htdocs, in apache2. It's that simple!

?>


And that's it for this FAQ.. basic PHP for beginners

I hope you like it, stay tuned for Part 2!

-Monkey
__________________
System: My System
CPU
Athlon XP 2600+
Motherboard
Abit NF7-S v2
Memory
1GB(2x512) PC2100
Graphics Card
6600GT AGP 8x
Hard Drive
80GB IDE
Sound Card
Audigy 2
Power Supply
400W Generic
Case
Beige Mid-Tower
OS
WinXP Pro SP1
Monitor
15" LCD (Analog)

Last edited by xxmonkey321xx : 09-21-06 at 07:42 PM Reason: Added "You will need"
xxmonkey321xx is offline  
Old 09-29-06   #2 (permalink)
Linux Lobbyist
 
drummer4lifex's Avatar
 
amd ati

Join Date: May 2006
Location: Champaign, IL
Posts: 1,247

Rep: 102 drummer4lifex is acknowledged by manydrummer4lifex is acknowledged by many
Unique Rep: 73
FAQs Submitted: 6
Trader Rating: 2
Default

Great FAQ! I've always wondered where to start with PHP. This answered those questions. Also, it's not too far off from java in certain ways, but it seems to me that most programming is the same with just different syntax, functions, and managed/unmanaged memory allocation. Hopefully it's true so I can learn more languages than java (which I know very little).

rep+
__________________
Signatures are overrated.

System: My System
CPU
Opteron 165 CCBBE 0610
Motherboard
DFI LanParty Ultra-D
Memory
2x 1GB OCZ Gold DDR 500
Graphics Card
Sapphire X1900XT 512MB
Hard Drive
160GB WD Caviar
Power Supply
Hiper 580W UV Blue
CPU cooling
Swiftech Apogee
GPU cooling
Danger Den MAZE4 LP
OS
Ubuntu
drummer4lifex is offline  
 


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools



All times are GMT -5. The time now is 01:46 PM.


Overclock.net is a Carbon Neutral Site Creative Commons License

Terms of Service / Forum Rules | Privacy Policy | DMCA Info | Advertising | Become an Official Vendor
Copyright © 2009 Shogun Interactive Development. Most rights reserved.
Page generated in 0.12216 seconds with 8 queries