Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Monday, May 17

5 min Intro to PHP

If your interested in learning or playing with PHP. Here is a short introduction to get you started. I expect that you have some basic programming skills already. (or the will power to stay and play for a while)

Download It

If your using a window OS you will want an "XAMP" installation. It installs Apache, PHP and MySQL on windows. Most of them are simple: download, unzip and click the "start" executable. I like to use Uniform Server. I won't go into debugging apache in this article, but I will suggest that you shut off any program that uses the web server ports. (Visual Studio, IIS, Skype).

Alternatively you can play on any website you have, most will have php enabled.

Basic Things to know

  • Save your page with a .php extension
  • Surround your code with <?php ...code.... ?>
  • You can use <? ...code.... ?> but that is non-standards compliant
  • All statements in php must end with ";"
  • Variables start with $. IE: $username, $today, $yesterday, $i
  • Variables "live" to the end of page, but do not carry over into functions
  • Single line comments use //
  • Multi line comments use /* .... */
  • To add strings use "." (IE: $firstName . " " . $lastName)
  • To add numbers use "+" (IE: $age + 10)
  • Use print to print (IE: print "Hello " . $username)
  • Use echo to print (IE: echo "Hello " . $username)
If statements

if( boolean )
{
//...some code
}
elseif( boolean )
{
//...some code
}
else
{
//...other code
}

Loops

for($i=0;$i<10;$i++)
{
//...code
}

while( boolean )
{
// ...code
}

Variables, Sessions and Forms

Normal Variable: $username;
Session Variable: $_SESSION["username"]
Form Post Variable: $_POST["username"]
Form Get Variable: $_GET["username"]

Kill a session variable: $_SESSION["username"] = "";


Database

PHP normally uses mySQL, but each of the functions below have an equivalent function for most database systems.

$db_host = "localhost";
$db_user = "user";
$database = "dbname";
$db_passwd = "pass";
mysql_connect($db_host, $db_user, $db_passwd);
$q = mysql_query("select * from user");

while($row = mysql_fetch_object($q))
{
print $row->username;
}


Alternativly you can use mysql_fetch_row($q)...this will get an array of the field values and you can access them by $row[0], $row[1]....etc.

As with most high level languages, php has a number of functions available to it. You can search the very friendly documentation at www.php.net


Objects and Classes
Class DateUtils
{

function DateUtils()
{
//...constructor
}


function getToday($format)
{
return date($format);
}
}

And here is how to use the class

$util = new DateUtils();
print $utils->getToday();



What else would you like to know?

Followers