An Ongoing PHP & MySQL Tutorial Thread by JD Walker

Lesson #6: Generating dynamic pages with PHP.

So let's see what all this looks like when applied to our template.

?page=about
switch1.gif


?page=gallery
switch2.jpg


?page=news
switch3.gif



Now if you notice, if you just access your url without a query string, the page is blank. You have to make sure you add "case" for that if you are using the "switch" condition...

PHP:
case '':
   header('Location: ' . url . '/index.php?page=about'); //if there is no query string, send the browser to the about page
break;
 
Just spent all fuckin' weekend setting up my LAMP environment(fuckin' with dayum ProFTP, SSH, MySQL GUI client and /var/www rights) in a vm. I'm ready to dig in this PHP shit. JD, much props! :dance::dance::dance:

I'm the type of dude that learns best when I have a project which to apply my knowledge. Anybody have any good ideas for web application projects?
 
Just spent all fuckin' weekend setting up my LAMP environment(fuckin' with dayum ProFTP, SSH, MySQL GUI client and /var/www rights) in a vm. I'm ready to dig in this PHP shit. JD, much props! :dance::dance::dance:

I'm the type of dude that learns best when I have a project which to apply my knowledge. Anybody have any good ideas for web application projects?

Start with form processing. Forms are pretty much a necessity on any website these days. And BTW skip the email validation snippet I have in this tutorial and use the filter function instead.
 
Start with form processing. Forms are pretty much a necessity on any website these days. And BTW skip the email validation snippet I have in this tutorial and use the filter function instead.

I corrected ALL of your coding errors (e.g. mysql_real_escape_string() requires a database connection to work, you didn't create the database before attempting to create the table in your mysql scrtipt) AND I made your script alil more efficient. :D

Before:

PHP:
if(isset($_POST['register'])) 
{ 
    clean_reg($_POST); 
         
    $submit = $_POST; 
     
    if(empty($submit['name'])) 
    { 
        $errors[] = 'Please enter your name.'; 
    } 
    if(!empty($submit['name'])) 
    { 
        if(strlen($submit['name']) > $reg_len){ 
            $errors[] = 'Your username is too long.'; 
        } 
    } 
    if(empty($submit['email'])) 
    { 
        $errors[] = 'Please enter your email address.'; 
    } 
    if(!empty($submit['email'])) 
    { 
        if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $submit['email'])) { 
                 $errors[] = 'Please enter a valid email address'; 
        } 
        if(strlen($submit['email']) > $reg_len){ 
            $errors[] = 'Your email is too long.'; 
        } 
    } 
    if(empty($submit['password'])) 
    { 
        $errors[] = 'Please enter your password.'; 
    } 
    if(!empty($submit['password'])) 
    { 
        if(strlen($submit['password']) > $reg_len){ 
            $errors[] = 'Your password is too long.'; 
        } 
    } 
    if(empty($errors)) 
    { 
        $submit['password'] = $submit['password'] . $salt; 
        $submit['password'] = hash('sha512', $submit['password']); 
        $submit['date'] = time(); 
         
                //This block submits the data in to the database using a combination of PHP and MySQL language... 
        $query ="INSERT INTO `site_users` (`id`, `name`, `email`, `password`, `date`) 
            VALUES ('', '{$submit['name']}', '{$submit['email']}', '{$submit['password']}', '{$submit['date']}');"; 
        $result = mysql_query($query) or die(mysql_error()); 
         
        $_SESSION['register'] = array(); //We'll clear the Session data since we don't need it anymore 
         
        header('Location: ' . url . '/index.php?action=home'); //This generates a dynamic page after submission that takes to user to where ever you want them to go. This will be covered in a later tutorial.  
    } 
}

After:

PHP:
if(isset($_POST['register'])) 
{ 
	clean_reg($_POST);     
    $submit = $_POST; //Good security practice to copy the $_POST variable 
	$array_index = -1;
	$keys = array_keys($submit);
    foreach($submit as $val){
		++$array_index;
		$key = $keys[$array_index];
		if(empty($val)){			
			$errors[] = 'Please enter your '.$key;
		}
		if(strlen($val) > $reg_len){
			$errors[] = 'Your '.$key.' is too long';		
		}
	}
	if(!empty($submit['email'])){ //If the email field is not empty, let's make sure they have entered a legit email address 
        if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $submit['email'])) { //We are using regex again to make sure the email address matches the given pattern 
                 $errors[] = 'Please enter a valid email address'; 
        } 
    }
	 if(empty($errors)) 
    { 
        $submit['password'] = $submit['password'] . $salt; 
        $submit['password'] = hash('sha512', $submit['password']); 
        $submit['date'] = time(); 
         
                //This block submits the data in to the database using a combination of PHP and MySQL language... 
        $query ="INSERT INTO `site_users` (`id`, `name`, `email`, `password`, `date`) 
            VALUES ('', '{$submit['name']}', '{$submit['email']}', '{$submit['password']}', '{$submit['date']}');"; 
        $result = mysql_query($query) or die(mysql_error()); 
         
        $_SESSION['register'] = array(); //We'll clear the Session data since we don't need it anymore 
         
        header('Location: ' . url . '/index.php?action=home'); //This generates a dynamic page after submission that takes to user to where ever you want them to go. This will be covered in a later tutorial.  
    } 	
   	echo '<pre>', print_r($submit), '</pre>'; 
}

End result:

201mo1.png


On to the next tutorial.
 
I corrected ALL of your coding errors (e.g. mysql_real_escape_string() requires a database connection to work, you didn't create the database before attempting to create the table in your mysql scrtipt) AND I made your script alil more efficient. :D

I thought I included the connection script in this tutorial.

Also, isset & empty are much faster than array_keys, which is why I rarely use array_keys.

Also as stated in my previous post, replace:
PHP:
        if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $submit['email'])) { //We are using regex again to make sure the email address matches the given pattern 
                 $errors[] = 'Please enter a valid email address'; 
        }

with

PHP:
	if(!filter_var($submit['email'], FILTER_VALIDATE_EMAIL)){
		$errors[] = 'Please enter a valid email address'; 
	}

the eregi function will no longer be supported in PHP 6.
 
if you are going to go this route...

PHP:
    $array_index = -1;
    $keys = array_keys($submit);
    foreach($submit as $val){
        ++$array_index;
        $key = $keys[$array_index];
        if(empty($val)){            
            $errors[] = 'Please enter your '.$key;
        }
        if(strlen($val) > $reg_len){
            $errors[] = 'Your '.$key.' is too long';        
        }
    }

PHP:
    foreach($submit as $key => $value)
    {
    	if(isset($key)){ //Make sure key exists
    		if(!empty($value)){ //Make sure value is not empty
    			if(strlen($value) > $reg_len){
            		$errors[] = 'Your '.$key.' is too long';        
        		}
    		}elseif(empty($value)){
    			$errors[] = 'Please enter your '. $key;
    		}
    	}    	
    }

that's untested but you don't need to incrementing variable if you are using foreach on one array.
 
I thought I included the connection script in this tutorial.

Also, isset & empty are much faster than array_keys, which is why I rarely use array_keys.

Also as stated in my previous post, replace:
PHP:
        if (!eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', $submit['email'])) { //We are using regex again to make sure the email address matches the given pattern 
                 $errors[] = 'Please enter a valid email address'; 
        }

with

PHP:
	if(!filter_var($submit['email'], FILTER_VALIDATE_EMAIL)){
		$errors[] = 'Please enter a valid email address'; 
	}

the eregi function will no longer be supported in PHP 6.

You did include the connection script but, it wasn't until the table creation lesson further in the tutorial. The mysql_real_escape_string() function was discussed early in the tutorial.

I didn't see the filter_var() function.
 
if you are going to go this route...

PHP:
    $array_index = -1;
    $keys = array_keys($submit);
    foreach($submit as $val){
        ++$array_index;
        $key = $keys[$array_index];
        if(empty($val)){            
            $errors[] = 'Please enter your '.$key;
        }
        if(strlen($val) > $reg_len){
            $errors[] = 'Your '.$key.' is too long';        
        }
    }

PHP:
    foreach($submit as $key => $value)
    {
    	if(isset($key)){ //Make sure key exists
    		if(!empty($value)){ //Make sure value is not empty
    			if(strlen($value) > $reg_len){
            		$errors[] = 'Your '.$key.' is too long';        
        		}
    		}elseif(empty($value)){
    			$errors[] = 'Please enter your '. $key;
    		}
    	}    	
    }

that's untested but you don't need to incrementing variable if you are using foreach on one array.

Wow, I have to do some research on:

PHP:
foreach($submit as $key => $value)
 
Wow, I have to do some research on:

PHP:
foreach($submit as $key => $value)

foreach works very well on associative arrays and mulit dimensional arrays. But is you have this for example $_POST, an accociative array:

PHP:
array
(
   [name] => Quaid
   [site] => bgol
   [email] => quaid@bgol.com
)

so we have the key i.e. [name] and the value "Quaid"

The most effient way to loop through this type of array is to use foreach

PHP:
foreach($_POST as $key => $value)
{
     echo $key, ' ', $value, '<br />';
}

foreach will automatically increment trough the array until it reaches the end.

Not if you have a standard indexed array


PHP:
array
(
   [0] => Quaid
   [1] => bgol
   [2] => quaid@bgol.com
)

again, you can use
PHP:
foreach($_POST as $key => $value)
{
     echo $key, ' ', $value, '<br />';
}

OR a traditional for loop where you set the increment value. Keep in mind, by default it will only return values, not keys...

PHP:
for($i = 0; count($_POST) >$i; $i++)
{
   echo $_POST[$i], '<br />';
}

and you can set where the loop begins if you want

PHP:
for($i = 2; count($_POST) >$i; $i++)
 
Taking another look, this...

PHP:
    foreach($submit as $key => $value)
    {
    	if(isset($key)){ //Make sure key exists
    		if(!empty($value)){ //Make sure value is not empty
    			if(strlen($value) > $reg_len){
            		$errors[] = 'Your '.$key.' is too long';        
        		}
    		}elseif(empty($value)){
    			$errors[] = 'Please enter your '. $key;
    		}
    	}    	
    }

Can be reduced to this:
PHP:
foreach($submit as $key => $value)
{
     if(isset($value)){
        if(strlen($value) > $reg_len){
           $errors[] = 'Your '.$key.' is too long';
      }elseif(!isset($value)){
          $errors[] = 'Please enter your '. $key;
      }
}
 
This thread has been here for over a year and Ive never seen it...How the hell am I on here all the time and just miss threads like this...good stuff JD.
 
I was doing PHP research and I came across PEAR. A code repository makes sense. ???

Also, what framework do you recommend? http://www.phpframeworks.com/

Also, I noticed your PHP directory structure in your tutorial. I read there are different approaches to this. What's your rationale for your approach?
 
I was doing PHP research and I came across PEAR. A code repository makes sense. ???

Also, what framework do you recommend? http://www.phpframeworks.com/

Also, I noticed your PHP directory structure in your tutorial. I read there are different approaches to this. What's your rationale for your approach?

I picked up that structure from mentors when I first started out. I've never used any rebuilt frameworks, I got started before they came out with these now popular frameworks like cakephp and code ignitor, so I couldn't give you an informed opinion. Since the nature of the web is procedural my approach is procedural. You will eventually stumble upon these Procedural vs. OOP arguments and they get more heated than an IPhone vs. Android debate. Both have strengths and drawbacks. I code for speed and performance therefore I take the procedural approach. I rarely use OOP unless I'm doing a small api. OOP, while easier to maintain creates a lot of overhead, which it turn will eventually force hardware upgrade, exhibit A being this message board.
 
I was doing PHP research and I came across PEAR. A code repository makes sense. ???

Also, what framework do you recommend? http://www.phpframeworks.com/

Also, I noticed your PHP directory structure in your tutorial. I read there are different approaches to this. What's your rationale for your approach?

one more thing, I'm not going to scour through this thread but I believed I emphasized MVC. Which ever framework/approach you decide to use you should always adhere to MVC.
 
one more thing, I'm not going to scour through this thread but I believed I emphasized MVC. Which ever framework/approach you decide to use you should always adhere to MVC.

Haven't done any programming with MVC. Will research this and other design patterns.
 
I was doing PHP research and I came across PEAR. A code repository makes sense. ???

Also, what framework do you recommend? http://www.phpframeworks.com/

Also, I noticed your PHP directory structure in your tutorial. I read there are different approaches to this. What's your rationale for your approach?

I run lots of cakephp apps. I will say one thing and a lot of php programmers will agree...cakephp is a tricky bitch. But I run a lot of cakephp scripts and I would recommend it. Codeigniter is not bad as well..Im running a couple of scripts build with that as well. I can´t really way which on this list is best...but I can vouch for those two.
 
JD, I think you are a self hating, antiblack, antiafrican, bipolar , manic depressive brotha who probably needs some serious mental help but this thread is invaluable to me right now because of a project I am working on thanks playa.
 
Back
Top