Recent Articles

PHP Tutorial : Results Pagination

Among the most common tasks for a php CMS writer is to handle pagination.

Pagination is needed when there are many entries in the database and they can not be shown in a single page of results. A pagination navigation bar gives the user the ability to see a smaller list of entries.

Pagination is not as easy as it seems, expecially when dealing with seo friendly urls or multi language sites. However here’s a solution for pagination in php. Simple and up to the point:

First, we calculate the total amount of entries. Then the numbers of pages needed to show everthing. And, of course, we need to know how many results are to be displayed per page. Finally, we’ll print out the entries and links for next, previous and each individual page number.

MySql LIMIT clause accepts either one or two values. In this example we use two so it returns values between -say- 10 and 20. If you only use one value, as in LIMIT 10, it will return the first 10 results.

The second value is a quantity, not an index!
In other words, don’t do LIMIT 0,10 then LIMIT 10,20 then LIMIT 20,30: it won’t work. Instead, use LIMIT 0,10, LIMIT 10,10, LIMIT 20,10.

<?php
//include database connection (check previous posts to get this one)
>include('dbConnection.php');
//get the number of total rows
$query = "SELECT * FROM TableName";
$result = mysql_query($query);
// Number of records found
$num_record = mysql_num_rows($result);
// Number of results per page
$display = 5;

if(isset($_GET['page'])) {
$currentPage = $_GET['page'];
}else{
$currentPage = 1;
}
//last page - we use ceil because page range is 1 to Max, this way page "2.5" becomes page 3
$lastPage = ceil($num_record/$display);
//limit in the query thing
$limitQ = 'LIMIT ' .($currentPage - 1) * $display .',' .$display;
//normal query and print results
$query = "SELECT * FROM TableName $limitQ";
$result = mysql_query($query);
//here you do your loop like
>while($row=@mysql_fetch_object($result)) {

print "$row->FieldName";
}
//pagination navigation (links)

//previous
>if ($currentPage == 1) {

print "Prev ";
} else {

print "<a href=pagename.php?page=1>First page</a> ";
$previousPage = $currentPage-1;

print "<a href=pagename.php?page=$previousPage>Previous</a>";
}

print " { Page $currentPage of $lastPage } ";
//for next pages links
>if ($currentPage== $lastPage) {

print "Next last";
} else {
$nextPage = $currentPage+1;

print " <a href=pagename.php?page=$nextPage>NEXT</a> ";

print " <a href=pagename.php?page=$lastPage>LAST</a> ";
}
?>

Now you can use this pagination to split your mysql results into multiple webpages, but there are better ways to handle this problem, as we’ll see in the future: keep in mind that right now we are reading all values every time, and this may burden our script. A better way would be to pre-count the number of results and then select only those we are going to show.

Also, for something like a comment page, an ajax pagination approach would probably be better. Again, we’ll get back at this in another tutorial -as always drop a comment if there is something you’d like to see explained more in depth.

Feedburner Feed

Hi,
This is a request for people reading my feed or who already subscribed.
Please use the feedburner feed so I will be able to see how many guy’s are following.

FEEDBURNER URL :

http://feeds2.feedburner.com/crivionweb/kRHa

PHP Tutorial : Membership script – Users Logout

Third and final step in our simple membership script. This is the easiest part: logging out users.

Just build a page called logout.php and put a link to it everywhere you want to give users the option to logout & here’s the function:

<?php
function logoutUser() {
session_unset();
session_destroy();
header("Location: homePage.php");
exit();
}
//here's how you put it in action


logoutUser();
?>

They’ll be redirected to the home page, with no active credentials.

Now you know how to build a basic membership script with php including registering, logging and of course logging out.

This script is not advanced, nor it is really secure but is clean, efficient and should give you an head start. Stay tuned for more to come!

PHP Tutorial : Membership script – Users Login

Welcome back to the simple php membership script tutorial.

Last time we saw how to create the php user registration function. We will continue today with the php login function and will also see how to check if a user is logged in or not.

<?php
function loginUser($user, $pass) {

if(empty($user) || empty($pass)) {
exit();
}else{
$user = addentities($user);
$pass = addentities($pass);
$sql = "select * from users where user = '$user' and pass = '$pass'";
$rs = mysql_query($sql);

if($rs) {

if(mysql_num_rows($rs) != 0) {
$row=@mysql_fetch_object($rs);
$_SESSION['logged'] = "yes";
$_SESSION['user'] = $user;

refreshPage(0, $_SERVER['PHP_SELF']);
}else{

print "Wrong username and password";
}
}
}
}
?>

Now, how simple is it to check if a user is logged in?

<?php

if(checkLogged() == false) {

print "You are not authorized to see this page, please login first!";
}elseif(checkLogged() == true) {

print "Welcome $_SESSION[user]";
}
?>

Please note that you must add the session_start(); function at the very begining of the script, before outputing anything else! Check this blog for detailed instructions on how to use sessions.

See you next time and happy coding!

PHP Tutorial : Membership script – Users Registration

Hi, fellow PHP coder. I’ve just created a brand new category called Complete Scripts. Here, you’ll find complete “Ready To Use” Solutions.

The first tutorial is about creating a membership script with user registration. I will write here a function which will do it. We will have database structure like this:

CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user` varchar(255) NOT NULL,
`pass` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

After this, here is the function to create new users and insert them into database: – first, create a .php page called functions.php

<?php
//Membership Script - Users Registration Function

function registerNewMember($user, $pass) {
$tableUsers = "users";

if(empty($user) || empty($pass)) {
exit();
}else{
$user = addslashes(mysql_real_escape_string($user));
$pass = addslashes(mysql_real_escape_string($pass));
$sql = "insert into $tableUsers values (null, '$user', '$pass')";
$rs = mysql_query($sql);

if($rs)
{
$result = "ok";
}else{
$result = "fail";
}
}
?>

Now we need to create a page with a form where users will type their desired user & pass (please note we need to include database connection file and functions one:

<?php
//include database connection


include('dbConnection.php');
//include functions.php


include('functions.php');
//check if registration form was submitted


if(isset($_POST['sb'])) {
extract($_POST);

if(registerNewMember($username, $password) == "ok")) {

print "You are now registered";
}else{

print "Not able to add new member";
}
}
?>
<form action="" method="POST">
Pickup  a new username : <input type="text" name="username"><br/>
Pikcup a brand new password : <input type="password" name="password"><br/>
<input type="submit" name="sb" id="sb" value="Register me!">
</form>

PS : For database connection please have a look at connecting to mysql database in PHP.

PHP Tutorial : Write to a file with fwrite

I showed you earlier in a older post how to open and read text contents from a file. Now it’s time to see how to write to a file using php function called fwrite().

<?php
$theFileToWriteTo = "textFile.txt";
$fileHandle = fopen($theFileToWriteTo, 'w') or die("cannot open the text file");
$textToWrite = "First text to write here\n";
fwrite($fileHandle, $textToWrite);
$textToWrite = "Second line to write here\n";
fwrite($fileHandle, $textToWrite);
fclose($fileHandle)
?>

Note that “\n” means new line!

PHP Tutorial : Multiple string replace with str_replace

Well, I already writed about str_replace php function but this tip is very usefull. To recap, the function it’s used to replace a string by using three paramaters : $stringToSearch, $stringToReplace, $intoString. I showed you how to use it in single operations but we can use it for multiple replaces in one place, by using arrays :

<?php
$searchArray = array("word1", "sound2", "etc3");
$replaceArray = array("word one", "sound two", "etc three");
$intoString = "Here is word1, as well sound2 and etc3";
//now let's replace


print str_replace($searchArray, $replaceArray, $intoString);
//it should print "Here is word one, as well sound two and etc three"

?>

I have to say this multiple replace “trick” is a very nice one!

See ya soon!

PHP Tutorial : Strpos and Strrpos

Basic thing, strpos and strrpos are two php functions which are used to find the position of first and/or last occurrence in a string – word (usefull for example when you want to build a function to get file extension). I hear you saying enough talking, let me see the available examples :

<?php
//get first occurrence

$string = "this string";
$find = "i";

print strpos($string,$find);//should print 2


print strrpos($string,$find); //should print 8

?>

PHP Tutorial : Get Protocol

I saw this problem/question on a few forums and I finded it useful to post on my blog too due to low results on google that gives you what you need. So,  how to get the protocol of a URL using php?  Have a look :

<?php
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';

print "The protocol is $protocol";
?>

Tadaaa!

PHP Tutorial : Ctype character type checking

Happy 1st June for those under 18

Yesterday I’ve found a nice function in php called ctype. And? What it does? Well, I see it as a replacement for regular expressions. PHP Ctype function checks for character type. Let’s hear the chars type we can check with that nice function  :

  • alphanumeric characters – ctype_alnum()
  • alphabetic characters      – ctype_alpha()
  • control characters           – ctype_cntrl()
  • numeric characters         – ctype_digit()
  • lowercase characters      – ctype_lower()
  • uppercase characters      – ctype_upper()
  • printable characters        – ctype_print()
  • any printable character but not whitespace or an alphanumeric – ctype_punct()
  • any printable characters but not space – ctype_graph()
  • whitespace characters    – ctype_space()
  • hexadecimal digit characters – ctype_xdigit()

Ok, long list huh? but usefull. I will show you a simple example which of course can be applied for all other ctype() functions :

<?php
//will check if a character type is digit

$toCheck = 1010;

if(ctype_digit($toCheck)) {

print "$toCheck is a number";
}else{

print "$toCheck is NOT a number";
}
?>