If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Newbies forum FAQ + Bookmarked threads

In recent releases of PHP, the php.ini directive "register_globals" is set to "Off" by default; so the recommended/preferred method of coding variables has changed. Many tutorials and texts/books were written prior to this change, so "I copied this from a book, perfectly" may not have any effect on your situation. You now must call variables from the "SUPERGLOBAL" arrays. Use $_POST['var'] for a POSTED form; $_GET['var'] to obtain a value from a URL. Cookies are $_COOKIE['var'], Session variables are now $_SESSION['var'], etc.

MySQL and PHP are pretty much a package deal; together with the Apache Server, they are often referred to as "AMP" - "Apache/Mysql/PHP". Yes, Tux lovers, if you run them on Linux, it's "LAMP" --- pretty !

MySQL is a Structured Query Language, much like MSSQL, and one of the best RDBMS' (Relational DataBase Management Systems). Before moving on check out PHP/MySQL functions at http://www.php.net/manual/en/ref.mysql.php

4 main functions are always used with MySQL and fetching data.

PHP Code:

mysql_connect(); or mysql_pconnect(); //Connect to a MySQL database.
// mysql_pconnect() maintains a permanent connection to the db server; mysql_connect() doesn't.

mysql_select_db('mydbase') // Selects a database named "mydbase" after connection is made.

mysql_query() // Creates a query to select data from a table or tables.

mysql_fetch_array(); or mysql_fetch_object(); // Both do exactly the same thing; extract data from a query.

// The difference is mysql_fetch_aray is done like this:

$var['index']

// and mysql_fetch_object is like this:

$var->index.

To select more than one row of data you will require a loop. The most common loops are while() or foreach(). For this example, we use while();

Assume we have a table named "news" in a database "mysite". We need to extract all the rows from "news" and display them in an HTML table for each article. There are 4 fields (or "columns") in this db table: id, title, date, and message.

PHP Code:

$con = mysql_connect("localhost","usernamehere","passwordhere");
// "localhost" is used if the db server is on the
//same computer the web server is on....
$selectdb = mysql_select_db("mysite",$con);
$query = mysql_query("SELECT * FROM news");

There you go... simple, isn't it? Though you can do it a differently with a foreach() statement. There are other functions, but these will take you a long way....
planetsim

4) Sessions and Cookies
Sessions and cookies are argued about all over the Board - which is better? Let's see why people are arguing.

Sessions:http://www.php.net/manual/en/ref.session.phpBefore a session can exist it first must be started ( session_start(); ) and then the session registered ( session_register(); ). Although you can bypass the session_register by using the $_SESSION or $HTTP_SESSION_VARS superglobal arrays.

This just counts how many times a visitor has visited that page. Sessions need to be registered but can also be unregistered using... session_unregister().

So, when to use sessions? Most of the time you should use a session in an admin or to keep track of a user on the site. Let's create a simple Session which stores a username, then gets validated on each page.

That example probably doesn't work; But you get the idea. What I haven't explained is that sessions only last as long as the browser is open, or until the session expires. About 5 minutes if browser inactive.

name - name of the cookie. value - value of the cookie. This value is stored on the clients computer; do not store sensitive information. expire - time the cookie expires. This is a unix timestamp (number of seconds since the epoch) In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). path - The path on the server in which the cookie will be available on. domain - The domain that the cookie is available secure - Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0.

5) Security
This isnt just PHP Related. For any person developing Server Side Web Applications should follow simple steps to stop people bypassing into areas they shouldnt be etc.

PHP - Make sure the register_globals = off. This will mean that you'll need $_POST etc.
The reason for this. Imagine you have an include include($page); in a querystring. What would happen if the user created a file on another server, and made it copy Database data, Passwords etc on your server by simply doing this index.php?page=http://website.com/deadlyscript.php
By using $_GET or $HTTP_GET_VARS, you limit only to querystrings.
Then by validating the data by using either a switch statement or if/else statement to make sure the data that is being entered from the querystring is correct.

Forms are a big problem. People can put clever yet annoying Javascript Functions in your script simply by entering in the Javascript code into a form.
You should always make sure you use strip_tags(); and use the htmlentities etc. Before using any information from a form. Some simple things like bin which gets inserted into your database can be fatal.

Never use cookies as a way to access your Site Admin, use sessions, this will make sure you always have to login via a form, before accessing the admin.
With Admins and accounts, make sure passwords are encrypted by using md5();. When needing to check the password just use md5() to see if its exact.

If you ever have forms that require Javascript to validate. Make sure you have some sort of php function that checks the same material that the Javascript is validating. Reason for this is Javascript could be off, Javascript isnt always accurate.

Just following these simple steps can stop many fatal errors occuring, and keep your Web Site Secure.

If anyone else has things they think should be added to the list, please go right ahead.

When to use two-dimensional arrays?
I liked an example when i first learnt arrays, was a person, and we had got all his details. Eg, Name, Age, Location.
From there we can make sub arrays
name => array("Firstname","Surname");
age => "40";
location array("Address" => "7 Goodwill Ln",
"PostCode" => "2234";
);
Thats just an example.

Use is_numeric() to help validate data that is expected to be numeric.
It is also possible to treat the data as a string and use regex to check that all characters are valid.

Use htmlspecialchars() or htmlentities() when writing output that you arent certain of.
This takes care of insertion of html or malicious clientside scripting.
Use strip_tags() if you dont want any of these tags at all.

Remember to escape strings entered into databases.
You might want to use addslashes() if the data is not already escaped.
However, different database systems may require other ways to escape characters that could potentially allow SQL injection.

Storing md5() hashes as passwords doesnt necessarily add more security, but it does make it more difficult to obtain the user's original password if this password is intercepted.

Cookies are an acceptable means of authentication if you dont need much security, but be warned: they can be spoofed easily.
Using sessions can be better, but again these methods arent foolproof.
If you need something stronger, you'll have to use encryption, SSL, https etc

remember to test if it installed correctly by going to. http://localhost once you have started the apache server.

From there you'll need to install PHP once again you can goto the site i suggested it has how you install it, the tutorial is quite old yet shouldnt be any different in installation.

If you dont want the tutorial.. goto http://php.net and download the PHP Installer. exe file about 900kb if i remember correctly.

Follow the prompts. When you get to which server you want to install.. Select apache, you should recieve an error saying something like, Couldnt get to requested server or something a long those lines.

That will mean you'll have to do this in the httpd.conf file.. Located in the Apache/Conf Directory.

Many of you more experinced programmers if your reading would know what its like when not planning a site, and in the middle of creating it, you want more features in it, eventually you keep adding them, and you have no idea when your project will finish, because as your adding your new features, your fixing code that wont work with the original design.

Ok so why Plan?
If you read the paragraph above you'd see what kinda mess you could become of not planning. Planning is a crucial step in creating your website.

So what do i plan?
Before we start planning. Brainstorm ideas, you should have some idea on what the site is about and title.

Get ideas on:
What you want in the site
How you want data to be displayed
What language you want to use.
How long each step should take (Not really important but can give you some sort of timeframe of the project)
What things require a database

Planning
After brainstorming you should now plan your ideas.
First id plan your database design or flatfile system. Which ever method you'll be using.

When designing, make sure you do it on paper, so you know if your gonna have relationships between tables. (This is a must it can make those queries a lot easier)

After designing the database its graphics time. Im not graphic designer, but a good way of creating your main design is to create the page and how its gonna look, then cut it up(I use Photoshop) not sure on what other people have but most have the feature of cutting the image.

Once you have graphics, design the site in html. This way you have the Graphics and HTML done, its only the php. Most newbies love having html code with there php code, eventually most grow out of it (yay).

Then its all php code the rest of the way.

Now once you have planned your site, dont add features until the project is finished. This way you can go back on the plan and add it. Check if theres relationshipts / extra tables needed and/or graphics needed.

Then you can code it.

The smart programmers do this, its why they can finish that project fast and things work smoothly. You can see when a programmer isnt smart its when they have errors, 6times out of 10 its when a programmer has added a new feature.

Since $_SESSION is always available, it doesn't need to be declared global.

Also, as the manual strongly notes, it's not a good idea to go mixing $_SESSION with session_register(), session_is_registered() and session_unregister();. They don't do anything that can't be done with the $_SESSION array: