A Tutorial for the Newbies
1) "My variables are empty" OR "My script won't work"
"$somevar is blank"
"I copied this script & it won't work"
"I changed hosts/servers & now my script doesn't work"
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.
EXAMPLE:
Script one: form.php---[/i]
echo "<form action=\"handle.php\" method=post>";
echo "What's your first name? <input type=text name=FName>";
echo "<br><input type=submit name=submit value=submit>";
Script two: handle.php---
echo $name; //THIS WON'T WORK!
echo $_POST['FName']; //This returns the value entered in Script One
dalecosp
Remember that $POST, $GET, $SERVER, $FILES, $_REQUEST, etc., are only valid if your PHP version is > 4.0 --- otherwise use $HTTP_POST_VARS, $HTTP_GET_VARS, $HTTP_SERVER_VARS, $HTTP_POST_FILES, etc.
planetsim
Reference: http://www.php.net/variables.external
2) MAIL: "Can I send mail with PHP?"
"I want to mail a form..."
The basics of the mail tag:
mail(string to, string subject, string message, string additional_headers);
Headers can be any of the following, (and some others):
MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1
From:
Cc:
Bcc:
EXAMPLE: A Form with Mailed Results
//The Form --- "form.html"
<form action="mail.php" method="post">
Email: <input type="text" name="frmail">
Message: <textarea name="msg"></textarea>
Subject: <input type="text" name="subj">
<input type=submit name="submit" value="Send">
</form>
//The mail script --- "mail.php"
$to = "you@isp.com";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: ".$_POST['frmail']."\r\n";
$mail = @mail($to,$_POST['subj'],$_POST['msg'],$headers);
// The "@" sign before the mail() call suppresses printing of errors
// that may occur. The test below will check for errors instead:
if(!$mail){
echo "Email not sent! Please try later...";
}else{
echo "Mail sent successfully!";
}
Reference: http://www.php.net/manual/en/function.mail
planetsim
3) MYSQL/database:
"How do I..."
"Getting info from a database..."
"?Select * from ?, huh?"
Using MySQL and formatting its data
[i]MySQL and PHP are pretty much a package deal; together with the Apache Server, they are often referred to as "AMP" - "Apache/Mysql/PHP". [size=1]Yes, Tux lovers, if you run them on Linux, it's "LAMP" --- pretty :cool: ![/size]
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 [url]http://www.php.net/manual/en/ref.mysql.php[/url]
[b]4 main functions[/b] are always used with MySQL and fetching data. [/i]
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: [b]id, title, date,[/b] and [b]message[/b].[/i] [code=php] $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");
// Creates an array of items with keys corresponding to table columns...
while($row = mysql_fetch_array($query)){
//Create the HTML table
echo "<table><tr><td>NewsID: ".$row[id]." Title:".$row[title].";
echo "</td></tr><tr><td>Date: ".$row[date]."<br />".$row[message]."</td></tr></table><br />";
}[/code]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.php
Before 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.
Here is a simple session code:
<?php
if (!session_is_registered('count')) {
session_register('count');
$count = 1;
}
else {
$count++;
}
?>
Hello, Visitor! You have seen this page <?php echo $count; ?> times....<p>
To continue, <A HREF="nextpage.php?<?php echo strip_tags (SID)?>">click here</A>
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.
//HTML Form to log in...
<form action="login.php" method="post">
Username <input type="text" name="user"><br />
Password <input type="password" name="pass"><br />
<input type="submit" name="submit" value="login"></form>
//end of form
//login.php
#check if account exists
$qstring="SELECT * FROM users WHERE username = '";
$qstring.=$_POST['user']."' AND password = '".$_POST['pass']."'");
$qry = mysql_query($qstring);
$numrows = mysql_num_rows($qry);
if($numrows < 1){ // If no return fr. database, the account doesn't exist....
}else{
session_start(); // start the session...
$_SESSION['user'] = $_POST['user']; // Registers the session user. If the POSTed username was "badman",
// then $_SESSION['user']=="badman"
}
//End of Validating
//The Check log
function checkLog(){
global $_SESSION;
if(session_is_registered("user")){
#add code to validate the user in the db
}else{
session_unregister("user"); // unregister the session
header("location: index.php"); // send them to the "home 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.
O.K. now... Cookies!!
Reference:http://www.php.net/manual/en/function.setcookie.php
Cookies are simpler than Sessions; Site Administration scripts shouldn't use them, but they're great for forums, etc.
Creating a Cookie
setcookie(); // Will create the Cookie
$_COOKIE['somename']; //Will get the cookie name and validate it when necessary.
O.K. --- the basics of setcookie();
setcookie ( name , value , expire , path , domain , secure);
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.
Example:[/i]
setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".example.com", 1);
This one only works on a secure connection. It will be saved in /~rasmus/.
The Cookie will only work the domain "example.com".
setcookie ("TestCookie", $value,time()+3600); /* expire in 1 hour */
Will Work anywhere as long as it's on the same domain, e.g. "phpbuilder.com".
Seeing the Cookies Value:
if(empty($_COOKIE['cookie'])){
$var = "phpbuilder";
setcookie("cookie",$var,time()+60*60); #lasts 1 hr
}else{
echo $_COOKIE['cookie']; #Prints "phpbuilder"
}
That's it, really. Like I said, not as complex as Sessions, but you can see why cookies shouldn't be used for things like Site Admin.