Introduction

This being the first of the New Guy's "PHP Helper", I would like to discuss some topics that are frequently requested around the PHPBuilder.com discussion forum. I will also be explaining some common errors on a very basic level. With each article posted you will see that the list of common problems and errors keeps growing, and we'll attempt to help you solve these potential problems as we go along.
If you don't know me, allow me to introduce myself--I am but a simple helper on the PHP Builder forums. While I don't know everything, I will be sure to help you out even if it means I have to learn something new myself. We are all here to learn, and I hope that as you learn, so will I. I hope this series will help you--the novice PHP programmer--learn to use PHP productively.
With each article, an index will be available on the first page which outlines what issues will be discussed in the article. If you would like to suggest an issue for a future article, feel free to contact me at: bpwebman (at) gmail (dot) com. So with no further ado, the first article.

Index of Issues

 

Those of you who are new to PHP programming and are using MySQL may run into many problems in getting started. Of course most of us wish to gather some data from the database and view it in a browser. Some times we run into problems where this just won't work. One of the most frequent problems I have seen is the "Not a valid result resource" error provided by MySQL. Thankfully I can tell you how to work through it to get what you want done.
Basically when you run a query on the MySQL server, the result is returned. That's fairly obvious, right? So let's look at some queries:

SELECT * FROM `table_name` ORDER BY column_title DESC;

SELECT column_title, column_title, column_title, column_title
    FROM `table_name` ORDER BY column_title DESC;

SELECT column_title FROM `table_name` ORDER BY column_title DESC;

The first query will select ALL column data in the table referenced. The second will only grab the column data specified. And the third is the most basic query of all--it will select only the one columns data in the table. Now, with that, if you limit the third query to one row to be returned, the result will be the data you're after. So let's say we have a table with the following setup:


Table Name: members
|  id  | Username       |  Password      |
+------+----------------+----------------+
|  1   | patterson_b    | password1      |
|  2   | killer_bee     | pbcup          |
+------+----------------+----------------+

Let's say we want to grab the password of the first user in the table. We would run the following query:

$query = "SELECT Password FROM `members` ORDER BY id ASC LIMIT 1";
$result = mysql_query($query);
echo $result;
The code above will run a query on the database and grab the first password in the table.  When we echo the variable $result, we will get "password1."  Let's look at another snippet of code:

Code: $query = "SELECT * FROM `members` ORDER BY id DESC"; $result = mysql_query($query); echo $result;

What we're doing there is running the query on the database and getting some data back as a result, and then we print the result of the query.
Now, what we should see (if the query is working properly) is something like:
Resource ID #?? where "??" is equal to an integer. If that is not the output you get, then you have to add a die statement to the query to see what your query error is. So your code could look like:

$query = "SELECT * FROM `members` ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());

The mysql_error() will spit out the exact error that mysql encounters. If you would like even more information, you can use mysql_errno() to give you the error number that corresponds to the error. This is helpful for googling for answers to your problems.
If you get an actual result, not a resource ID or anything like that, but something that you expect, then you need to select more than one column and more than one row. Here's some examples of working & non-working code.

// Basic Connection settings
$conn = @mysql_connect('localhost', 'user', 'pass');
if($conn)
{
    mysql_select_db('test_database', $conn);
}
else
{
    echo "Couldn't connect to database!!";
}

$query1 = "SELECT * FROM `test_table` ORDER BY id DESC";
$result1 = mysql_query($query1);
echo $result1.'<hr>';

$query2 = "SELECT id FROM `test_table` ORDER BY id DESC LIMIT 1";
$result2 = mysql_query($query2);
echo $result2.'<hr>';

$query3 = "SELECT id, name FROM `test_table` LIMIT 0,2";
$result3 = mysql_query($query3);
echo $result3;
        That will output:

Resource ID#?? -------------- 1 -------------- Resource ID#??

Note: The "??" will be replaced with a numerical value. It is dependant upon other factors and can not be determined.

Forms & Submission
Forms are used a lot, and with PHP you can do some pretty neat stuff. I am going to assume that you know how to create a valid HTML form, and just need help with the processing side of it. To get things started, let's create a form:


<form action="" method="post">
    Name: <input type="text" name="name">
    Age: <input type="text" name="age">
    <input type="submit" name="Submit" value="I Love Chocolate">
    <input type="submit" name="Submit" value="I Hate Chocolate">
    <input type="submit" name="Submit" value="Chocolate = Zits">
</form>

So we'll start with some easy processing--we'll get the name and age first:


<?php

$name = $_POST['name'];
$age = $_POST['age'];

?>

Easy right? All the posted information is added to a global array that is called: $_POST. It's a predefined constant. Although you can use it as you wish, it's main use is for values coming from an HTML form. Now, the $_POST[] is for the newer versions of PHP. If you are using an older version ( PHP <= 4.3.1), then you would want to use $HTTP_POST_VARS[]. If we change the form method from "post" to "get", we need to use $_GET[] and $HTTP_GET_VARS[] respectively. Using "get", all the values are passed through the URL so anyone can see them.
So now we have the name and age. But what about the Chocolate button? It's the same as all the others--you just refer to it using the name value. We named our button "Submit", so we'll get it using $_POST['Submit']. Each form value must be referred to using $_POST['name of field'].


<?php

$name = $_POST['name'];
$age = $_POST['age'];
$chocolate = $_POST['Submit'];

echo "Hello ".$name."!!  You are ".$age." year(s) old.<br><br>
    Did you know: ".$chocolate." too!!!";

?>

Using the following inputs:
Name: Brett
Age: 21
Button Pressed: "I Love Chocolate"
It will output:
Hello Brett!! You are 21 year(s) old. Did you know: I Love Chocolate too!!
It's that easy. You can make your forms as intricate and in-depth as you want. I haven't seen people ask too many questions about radio buttons, checkboxes, and lists, so I guess it's not that difficult to grasp. If I see requests for it, I'll revisit this topic.

So now you have an array of information, but you want to sort it alphabetically. Luckily, PHP has built-in functions to do just this. There are many that are available, so I'll just breeze through the basics of them. You can find lots of info about the sorting of arrays at PHP.net.
sort()
The sort() function just sorts the array. So if we have:


$companies = array("Microsoft", "HP", "Apple", "Dell", "Creative");
sort($companies);
print_r($companies);

Will output:

Array
(
    [0] => Apple
    [1] => Creative
    [2] => Dell
    [3] => HP
    [4] => Microsoft
)

rsort()
This does the same as sort(), except in reverse. So:


$companies = array("Microsoft", "HP", "Apple", "Dell", "Creative");
rsort($companies);
print_r($companies);

Will Output:


Array
(
    [0] => Microsoft
    [1] => HP
    [2] => Dell
    [3] => Creative
    [4] => Apple
)

asort() and arsort()
These sort arrays keep the index intact. asort() sorts normally, and arsort() sorts in reverse. Here's the code and the output:


$companies = array("Microsoft", "HP", "Apple", "Dell", "Creative");
asort($companies);
print_r($companies);

echo '<br>';

$companies = array("Microsoft", "HP", "Apple", "Dell", "Creative");
arsort($companies);
print_r($companies);

This will output:


Array
(
    [2] => Apple
    [4] => Creative
    [3] => Dell
    [1] => HP
    [0] => Microsoft
)

Array
(
    [0] => Microsoft
    [1] => HP
    [3] => Dell
    [4] => Creative
    [2] => Apple
)

ksort()
This will sort an array by its key. So we'll modify our original code to be:


$companies = array("F"=>"Microsoft", "K"=>"HP", "A"=>"Apple", "Z"=>"Dell", "Q"=>"Creative");
ksort($companies);
print_r($companies);

Will output:


Array
(
    [A] => Apple
    [F] => Microsoft
    [K] => HP
    [Q] => Creative
    [Z] => Dell
)

That's all there is to sorting arrays!! Now you can get more and more complex with them, but I just showed you the basics of sorting the arrays in ascending and descending order. As always, reference the online PHP manual at PHP.net if you need more in-depth instructions as to exactly what parameters you can add to the sort functions, or for additional sort functions.

Dynamic Tables
Possibly one of the easiest things in PHP to do is to dynamically populate a table. We've got information that is pulled from a data source (database, directory, whatever) and now we want to create a table that is dynamic, that is, a table that grabs its data on the fly, dynamically. But we just want to specify the number of columns and let PHP do the work. I'll step you through how to do it and go over what it does. I'll use a script that I created which indexes pictures--if you need help customizing the script, just drop me a PM via the PHPBuilder forums. My tag on PHPBuilder is bpat1434.
Here's what we'll be creating:

I'll just give you the code that I'm using and focus on the table creation as that is the main point of this tutorial:

$num_of_images = 52;
$title = "Halloweenfetst - 2003: October 31, 2003 - New Jersey";
$vlink = "#009900";
$alink = "#006600";
$link = "#0066CC";
$text = "#FFFFFF";
$bgColor = "#006699";
$month_image_path = './images/thumbs/2003halloweenFest';
$up_one_level = '../index.html';
$month_path = './imageLoader?';

echo '<html>
  <title>'.$title.'</title>
  <body bgcolor="'.$bgColor.'" vlink="'.$vlink.'" alink="'.$alink.'" link="'.$link.'">
  <p align="center">
    <a href="'.$up_one_level.'"><font face="Webdings" color="'.$text.'">1<font></a>
  </p>

That sets everything up for us. Now, we'll work with the images and display them in table format.

So we begin with our table and our table row tags:


<table>
  <tr>';
    ALL THE CODE IN THE NEXT TWO STEPS WILL GO HERE!!
echo '</tr>
    </table>';

So we've got our table and a row, but we still need to add our images to the table. We want to show five images across each row, in as many rows as we need to display them. Since we know the number of images we have, let's create a for() loop, and put it inside of the table row tags from above.:


for($x=1; $x<=$num_of_images; $x++)
{
}

That line says we're going to increment $x by 1 each time we go through the loop. And, we'll go through it until $x is equal to, but not greater than, the $num_of_images variable we set (52). So we're going through the loop 52 times. We still need to add the images to the table, so we add this inside our for loop:


     echo '<td><a href="'.$month_path.'img='.check($x).'.jpg">
          <img border="0" src="'.$month_image_path.check($x).'.jpg"></a></td>';

Now we get all 52 images in one row. Not what we want, but close. Now, how can we make it so that every 5th picture ends the row, and starts a new one? We are going to use the Modulus arithmetic operand (in other words, we're looking to see what the remainder of a division is). The operand sign is the percent sign (%). So we set up our if() statement thusly:


    if($x % 5 == 0)
    {
        echo '</tr>
        <tr>';
    }

At this point, our code should look like this:


$num_of_images = 52;
$title = "Halloweenfetst - 2003: October 31, 2003 - New Jersey";
$vlink = "#009900";
$alink = "#006600";
$link = "#0066CC";
$text = "#FFFFFF";
$bgColor = "#006699";
$month_image_path = './images/thumbs/2003halloweenFest';
$up_one_level = '../index.html';
$month_path = './imageLoader?';

echo '<html>
  <title>'.$title.'</title>
  <body bgcolor="'.$bgColor.'" vlink="'.$vlink.'" alink="'.$alink.'" link="'.$link.'">
  <p align="center">
    <a href="'.$up_one_level.'"><font face="Webdings" color="'.$text.'">1<font></a>
  </p>

  <table>
    <tr>';

      for($x=1; $x<=$num_of_images; $x++)
      {
        echo '<td><a href="'.$month_path.'img='.check($x).'.jpg">
          <img border="0" src="'.$month_image_path.check($x).'.jpg"></a></td>';
        if($x % 5 == 0)
        {
          echo '</tr>
          <tr>';
        }
      }
            
    echo '</tr>
      </table>';

That's all there is to it. With that our code is complete and the photo gallery should be working perfectly. As always, if you run into problems, feel free to post questions about it here, or contact me directly. See you next time!