Thursday, March 20, 2014

FONT AWESOME BOOTSTRAP

Font Awesome is really Awesome because it contain what you have been looking for to enhance your Web Development both for Desktop and Mobil Applications

After you get up and running, you can place Font Awesome icons just about anywhere with the <i> tag. Some examples appreciatively re-used from the Bootstrap documentation



Try this out copy and paste this in the in between the head tag <head></head>

<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"
 
 Copy and past this on in between the body tag <body></body> and see what i am talking about for a start.
 
<p><i class="fa fa-camera-retro fa-lg"></i> fa-camera-retro</p>
<p><i class="fa fa-camera-retro fa-2x"></i> fa-camera-retro</p>
<p><i class="fa fa-camera-retro fa-3x"></i> fa-camera-retro</p>
<p><i class="fa fa-camera-retro fa-4x"></i> fa-camera-retro</p>
<p><i class="fa fa-camera-retro fa-5x"></i> fa-camera-retro</p> 
 
<ul class="nav nav-pills nav-stacked">
  <li class="active"><a href="#"><i class="fa fa-home fa-fw"></i> Home</a></li>
  <li><a href="#"><i class="fa fa-book fa-fw"></i> Library</a></li>
  <li><a href="#"><i class="fa fa-pencil fa-fw"></i> Applications</a></li>
  <li><a href="#"><i class="fa fa-cogs fa-fw"></i> Settings</a></li>
</ul> 
 
<ul class="fa-ul">
  <li><i class="fa-li fa fa-check-square"></i>List icons (like these)</li>
  <li><i class="fa-li fa fa-check-square"></i>can be used</li>
  <li><i class="fa-li fa fa-spinner fa-spin"></i>to replace</li>
  <li><i class="fa-li fa fa-square"></i>default bullets in lists</li>
</ul> 
 
<i class="fa fa-quote-left fa-2x pull-left fa-border"></i>
Use a few styles together and you'll have easy pull quotes or a great introductory article icon.
 
<i class="fa fa-spinner fa-spin"></i>
<i class="fa fa-refresh fa-spin"></i>
<i class="fa fa-cog fa-spin"></i>
 
 Best of Look
 

Monday, February 17, 2014

Cool Pop Up on Page Load

http://forum.jquery.com/topic/a-very-simple-popup-box-div

Monday, January 20, 2014

Generate An Authentication Code in PHP

This basic snippet will create a random authentication code, or just a random string.

 
?php
# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
    $pos = rand(0,36);
    $str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?>

Wednesday, December 4, 2013

How can I limit the number of rows returned by MySQL? (Pagination)

This is one of the most asked question I've ever seen in dev communities! it's called pagination.
It's been asked too many times, so I thought this might be the first tip I should add here !
Simply, all you have to do is add the LIMIT clause to your MySQL query and it should work fine!
Sounds easy, doesn't it ? ;)

Now all let's see an example:


PHP Code:
<?PHP
//this query will fetch 3 records only!
$fetch mysql_query("SELECT * FROM table LIMIT 3")or
die(
mysql_error());
?>


so the above query will fetch only the first 3 rows in the table.

There is another way to use LIMIT (which is the one we need!):

PHP Code:
<?PHP
$fetch 
mysql_query("SELECT * FROM table LIMIT 0, 10")or
die(
mysql_error());
?>


This code will allow you to fetch 10 records starting from record 0 (the first), this is helpful when you have hundreds of records in the table and you want to show only part of it or make every set of the result in a page.
Now how can you make the next page show the next 10 records?
you simply have to store the value of the starting row in a variable and pass it in the URL as a GET variable.
We also have to check if there was a value already passed or not so we can set a default value in case it wasn't (zero to start from first row):

PHP Code:
<?PHP
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
  
//we give the value of the starting row to 0 because nothing was found in URL
  
$startrow 0;
//otherwise we take the value from the URL
} else {
  
$startrow = (int)$_GET['startrow'];
}
?>



Now your query should have this new variable ($startrow) in the LIMIT clause

PHP Code:
<?PHP
//this part goes after the checking of the $_GET var
$fetch mysql_query("SELECT * FROM table LIMIT $startrow, 10")or
die(
mysql_error());
?>



Now to see the next 10 records you should have a link which will add 10 to $startrow so you can view the next 10 records

PHP Code:
<?PHP
//now this is the link..
echo '<a href="'.$_SERVER['PHP_SELF'].'?startrow='.($startrow+10).'">Next</a>';
?>


It's that simple !!
if you want to have a previous link, just substract 10 from $startrow like this:

PHP Code:
<?PHP
$prev 
$startrow 10;

//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
    echo 
'<a href="'.$_SERVER['PHP_SELF'].'?startrow='.$prev.'">Previous</a>';
?>

Tuesday, December 3, 2013

Learn How to Paginate Data with PHP

I can remember years ago when I first began coding in PHP and MySQL, how excited I was the first time I got information from a database to show up in a web browser. For someone who had little database and programming knowledge, seeing those table rows show up onscreen based on the code I wrote (okay so I copied an example from a book — let’s not split hairs) gave me a triumphant high. I may not have fully understood all the magic at work back then, but that first success spurred me on to bigger and better projects.
While my level of exuberance over databases may not be the same as it once was,
ever since my first ‘hello world’ encounter with PHP and MySQL I’ve been hooked
on the power of making things simple and easy to use. As a developer, one problem
I’m constantly faced with is taking a large set of information and making it easy
to digest. Whether its a large company’s client list or a personal mp3 catalog,
having to sit and stare at rows upon rows upon rows of data can be discouraging
and frustrating. What can a good developer do? Paginate!

1. Pagination

Pagination is essentially the process of taking a set of results and spreading
them out over pages to make them easier to view.
example 1
I realized early on that if I had 5000 rows of information to display not only
would it be a headache for someone to try and read, but most browsers would take
an Internet eternity (i.e. more than about five seconds) to display it. To solve
this I would code various SQL statements to pull out chunks of data, and if I was
in a good mood I might even throw in a couple of “next” and “previous” buttons.
After a while, having to drop this code into every similar project and customize
it to fit got old. Fast. And as every good developer knows, laziness breeds inventiveness
or something like that. So one day I sat down and decided to come up with a simple,
flexible, and easy to use PHP class that would automatically do the dirty work for
me.
A quick word about me and PHP classes. I’m no object-oriented whiz. In fact I hardly
ever use the stuff. But after reading some OOP examples and tutorials, and some
simple trial and error examples, I decided to give it a whirl and you know what?
It works perfectly for pagination. The code used here is written in PHP 4 but will
work in PHP 5.

2. The Database

Gotta love MySQL. No offense to the other database systems out there, but for
me all I need is MySQL. And one great feature of MySQL is that they give you some
free sample databases to play with at
http://dev.mysql.com/doc/#sampledb.
For my examples I’ll be using the world database (~90k zipped) which contains over
4000 records to play with, but the beauty of the PHP script we’ll be creating is
that it can be used with any database. Now I think we can all agree that if we decided
not to paginate our results that we would end up with some very long and unwieldy
results like the following:
example 2
(click for full size, ridiculously long image ~ 338k)
So lets gets down to breaking up our data into easy to digest bites like this:
example 3
Beautiful isn’t it? Once you drop the pagination class into your code you can
quickly and easily transform a huge set of data into easy to navigate pages with
just a few lines of code. Really.

3. Paginator.class.php

Our examples will use just two scripts: paginator.class.php, the reusable
pagination script, and index.php, the PHP page that will call and use
paginator.class.php. Let’s take a look at the guts of the pagination class
script.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
<?php
class Paginator{
    var $items_per_page;
    var $items_total;
    var $current_page;
    var $num_pages;
    var $mid_range;
    var $low;
    var $high;
    var $limit;
    var $return;
    var $default_ipp = 25;
    function Paginator()
    {
        $this->current_page = 1;
        $this->mid_range = 7;
        $this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
    }
    function paginate()
    {
        if($_GET['ipp'] == 'All')
        {
            $this->num_pages = ceil($this->items_total/$this->default_ipp);
            $this->items_per_page = $this->default_ipp;
        }
        else
        {
            if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
            $this->num_pages = ceil($this->items_total/$this->items_per_page);
        }
        $this->current_page = (int) $_GET['page']; // must be numeric > 0
        if($this->current_page < 1 Or !is_numeric($this->current_page)) $this->current_page = 1;
        if($this->current_page > $this->num_pages) $this->current_page = $this->num_pages;
        $prev_page = $this->current_page-1;
        $next_page = $this->current_page+1;
        if($this->num_pages > 10)
        {
            $this->return = ($this->current_page != 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page\">« Previous</a> ":"<span class=\"inactive\" href=\"#\">« Previous</span> ";
            $this->start_range = $this->current_page - floor($this->mid_range/2);
            $this->end_range = $this->current_page + floor($this->mid_range/2);
            if($this->start_range <= 0)
            {
                $this->end_range += abs($this->start_range)+1;
                $this->start_range = 1;
            }
            if($this->end_range > $this->num_pages)
            {
                $this->start_range -= $this->end_range-$this->num_pages;
                $this->end_range = $this->num_pages;
            }
            $this->range = range($this->start_range,$this->end_range);
            for($i=1;$i<=$this->num_pages;$i++)
            {
                if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
                // loop through all pages. if first, last, or in range, display
                if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
                {
                    $this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
                }
                if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
            }
            $this->return .= (($this->current_page != $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All')) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page\">Next »</a>\n":"<span class=\"inactive\" href=\"#\">» Next</span>\n";
            $this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
        }
        else
        {
            for($i=1;$i<=$this->num_pages;$i++)
            {
                $this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
            }
            $this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
        }
        $this->low = ($this->current_page-1) * $this->items_per_page;
        $this->high = ($_GET['ipp'] == 'All') ? $this->items_total:($this->current_page * $this->items_per_page)-1;
        $this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
    }
    function display_items_per_page()
    {
        $items = '';
        $ipp_array = array(10,25,50,100,'All');
        foreach($ipp_array as $ipp_opt)    $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
        return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value;return false\">$items</select>\n";
    }
    function display_jump_menu()
    {
        for($i=1;$i<=$this->num_pages;$i++)
        {
            $option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
        }
        return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page';return false\">$option</select>\n";
    }
    function display_pages()
    {
        return $this->return;
    }
}
?>
Phew, that’s a lot of code! But don’t worry, I’ll explain what all the
different parts do and how they’re used.

4. Have a Little Class

Let’s begin at the beginning. First off we declare the class and give it a
name. Paginator should do it. And while we’re at it, let’s set some variables,
or properties in OOP speak, that our new paginator object will use.
01
02
03
04
05
06
07
08
09
10
11
class Paginator{
    var $items_per_page;
    var $items_total;
    var $current_page;
    var $num_pages;
    var $mid_range;
    var $low;
    var $high;
    var $limit;
    var $return;
    var $default_ipp = 25;
We start off our class by giving it a name, in this case “Paginator”, and
defining the variables (a.k.a the properties of an object) that we’ll be using.
When we create a new object using this class (a.k.a instantiating), the object
will have these properties and one of them, $default_ipp (the default number of
items per page), is also initialized to a value of 25.
Our class will have five methods, or
member functions, which do the heavy lifting; and they’re named Paginator, paginate,
display_items_per_page, display_jump_menu, and display_pages.
1
2
3
4
5
6
function Paginator()
{
    $this->current_page = 1;
    $this->mid_range = 7;
    $this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}
The Paginator function is also referred to as our constructor method, which just means when you
create a new paginator object, this function is also called by default. When we instantiate a new paginator
object, this initializes it with some default values. Here we set those
variables and check to see if we’ve changed the number of items per page to
display. If the items per page variable isn’t set in the URL’s query string ($_GET['ipp']),
we use the default number when the class was created.
The next method, the paginate function, is the Arnold Schwarzenegger, the Jean Claude Van Damme, the
meat of our class. The paginate method is what determines how many page
numbers to display, figures out how they should be linked, and applies CSS
for styling.
01
02
03
04
05
06
07
08
09
10
if($_GET['ipp'] == 'All')
{
    $this->num_pages = ceil($this->items_total/$this->default_ipp);
    $this->items_per_page = $this->default_ipp;
}
else
{
    if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
    $this->num_pages = ceil($this->items_total/$this->items_per_page);
}
The first part of this method determines the number of pages we’ll be
outputting and sets the number of items per page. First it tests to see if we
want to display all the items on one page. If so, it simply displays all the
items on one page and if not, it calculates the number of links it will need to
output, based on the number of items per page and the total number of items. It
also throws in some error checking to make sure that the number of items per
page is a numeric value.
1
2
3
4
5
$this->current_page = (int) $_GET['page']; // must be numeric > 0
if($this->current_page < 1 Or !is_numeric($this->current_page)) $this->current_page = 1;
if($this->current_page > $this->num_pages) $this->current_page = $this->num_pages;
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
The next part gets the page number we’re on and checks to make sure that it’s
a number in a valid range. It also sets the previous and next page links.
The rest of the paginate method is what does all the hard work. We check to
see if we have more than  ten pages (if($this->num_pages > 10)), ten
being a number that you can easily change. If
we don’t have more than ten pages, we simply loop from one to however many pages
we do have, and link them up accordingly. We don’t display any previous page or next page
links since we’re displaying all page numbers and this would be a bit redundant, but
we do display a link to all items. If we have more than ten pages, then
instead of displaying links to each and every page (if we had say 200 pages to
display, things might get a little ugly), we display links to the first and last
page and then a range of pages around the current page that we’re on. This is
where the variable (property) $this->mid_range comes into play. This variable tells the
paginator how many page numbers to display between the first and last pages. By
default this is set to seven, however you can change it to anything you like.
Just a note, the mid range value should be an odd number so the display is
symmetrical, but it can be even if you like. For example, let’s say we have 4000
rows of data in all, and we’re viewing 50 rows of data per page. That gives us
79 pages to display, but aside from the first and last pages we’re
only going to display links to three pages above and below the page we’re on. So
if we’re on page 29, the paginator will display links to page 1, 26, 27, 28, 29,
30, 31, 32, and 79 (don’t worry, if you want to jump to a specific page not in
that range I’ll explain how to do that a little later on). As you move
closer to the upper and lower page limits, the mid range adjusts itself so that
you always have at least the number of page links that mid_range is set for.
The next method, display_items_per_page, is an optional method that will display a drop
down menu that allows a visitor to change the number of items displayed per
page. The default values for the drop down menu are 10, 25, 50, 100, and
All. You can change the numeric values to anything you like, but if you want to
retain the ‘All’ option, it must not be changed
items per page.
1
2
3
4
5
6
7
function display_items_per_page()
{
    $items = '';
    $ipp_array = array(10,25,50,100,'All');
    foreach($ipp_array as $ipp_opt)    $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
    return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value;return false\">$items</select>\n";
}
The next method, display_jump_menu, is another optional method that displays a drop down
menu that will list all the page numbers available and allow a visitor to
jump directly to any page. Using our previous example, if we had a total of
79 pages to display, this drop down menu would list them all so that when
someone selects a page, it automatically will take them to it.
1
2
3
4
5
6
7
8
function display_jump_menu()
{
    for($i=1;$i<=$this->num_pages;$i++)
    {
        $option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
    }
    return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page';return false\">$option</select>\n";
}
The last method, display_pages, may be the shortest method, but it’s also one
of the most important. This method displays the page numbers on your page.
Without calling it, all the calculations would be done, but nothing would be
shown to your visitor. You need to
call this method at least once in order to display your pagination, but you can also
use it more than once if you like. For example, you could display the page
numbers above AND below your results for convenience. And convenience is
what its all about, no?

5. So How Do I Use This Thing?

There are three things you need to do in your index.php file before being
able to use your new paginator class.
  1. First, include the paginator class in the page where you want to use it.
    I like to use require_once because it ensures that the class will only be
    included once and if it can’t be found, will cause a fatal error.
  2. Next, make your database connections.
  3. Finally, query your database to get the total number of records that
    you’ll be displaying.
Step three is necessary so that the paginator can figure out how many records
it has to deal with. Typically the query can be as simple as SELECT COUNT(*)
FROM table WHERE blah blah blah.
You’re almost there. Now it’s time to create a new paginator object, call a
few of its methods, and set some options. Once you have your total record count
from step three above you can add the following code to index.php:
1
2
3
4
5
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9;
$pages->paginate();
echo $pages->display_pages();
Let’s break it down…
  • The first line gives us a shiny new paginator object to play with and
    initializes the default values behind the scenes.
  • The second line uses the query we did to get the total number of records and
    assigns it to our paginator’s items_total property. $num_rows is an array
    containing the result of our count query (you could also use PHP’s
    mysql_num_rows function to retrieve a similar count if you like).
  • The third line tells the paginator the number of page links to display. This
    number should be odd and greater than three so that the display is symmetrical.
    For example if the mid range is set to seven, then when browsing page 50 of 100,
    the mid range will generate links to pages 47, 48, 49, 50, 51, 52, and 53. The
    mid range moves in relation to the selected page. If the user is at either the
    low or high end of the list of pages, it will slide the range toward the other
    side to accommodate the position. For example, if the user visits page 99 of
    100, the mid range will generate links for pages 94, 95, 96, 97, 98, 99, and
    100.
  • The fourth line tell the paginator to get to work and paginate and finally the
    fifth line displays our page numbers.
If you decide to give your visitors the option of changing the number of items
per page or jumping to a specific page, you can add this code to index.php:
1
2
echo "<span style="\"margin-left:25px\""> ". $pages->display_jump_menu()
. $pages->display_items_per_page() . "</span>";
If you stopped here and viewed your page without adding anything else, you’d see
your page numbers but no records. Aha! We haven’t yet told PHP to display the
specific subset of records we want. To do that you create a SQL query that
includes a LIMIT statement that the paginator creates for you. For example, your
query could look like:
1
SELECT title FROM articles WHERE title != '' ORDER BY title ASC $pages->limit
$pages->limit is critical in making everything work and allows our paginator
object to tell the query to fetch only the limited number of records that we
need. For example, if we wanted to see page seven of our data, and we’re viewing
25 items per page, then $pages->limit would be the same as LIMIT 150,25 in SQL.
Once you execute your query you can display the records however you like. If you
want to display the page numbers again at the bottom of your page, just use the
display_pages method again:
1
echo $pages->display_pages();

6. More Features

As an added bonus, the paginator class adds “Previous”, “Next”, and “All”
buttons around your page links. It even disables them when you’re on the first
and last pages respectively when there are no previous or next pages. If you
like, you can also tell your visitors that they’re viewing page x of y by using
the code:
1
echo "Page $pages->current_page of $pages->num_pages";

Styling

Finally, you’re free to customize the look of your pagination buttons as much as
you want. With the exception of the current page button, all other page buttons
have the CSS class “paginate” applied to them while the current page button has,
can you guess, the “current” class applied to it. The “Previous” and “Next”
buttons will also have the class “inactive” applied to them automatically when
they’re not needed so you can style them specifically. Using these three classes
along with other CSS gives you tremendous flexibility to come up with a variety
of styling choices.
Styled:
example 4
Unstyled:
example 5

Wrapping Up

As you’ve seen with the pagination class and just a few lines of code you can
tame those giant database lists into manageable, easy to navigate, paginated
lists. Not only are they easier on the eyes but they’re faster not only to load
but to browse. Feel free to checkout a couple of demos at
example 1 and
example 2.

Submit Search query & get Search result without refresh (AJAX)


In order to submit a form, collect the results from the database and present them to the user without a page refresh, redirect or reloading, you need to:
  1. Use Ajax to Post the data from your form to a php file;
  2. That file in background will query the database and obtain the results for the data that he as received;
  3. With the query result, you will need to inject it inside an html element in your page that is ready to present the results to the user;
  4. At last, you need to set some controlling stuff to let styles and document workflow run smoothly.

So, having said that, here's an working example:

We have a table "persons" with a field "age" and a field "name" and we are going to search for persons with an age of 32. Next we will present their names and age inside a div with a table with pink background and a very large text.
To properly test this, we will have an header, body and footer with gray colors!

 index.php
<script type="text/javascript">
      $(function() {
        $("#lets_search").bind('submit',function() {
          var value = $('#str').val();
           $.post('db_query.php',{value:value}, function(data){
             $("#search_results").html(data);
           });
           return false;
        });
      });
    </script>

  </head>

  <body style="margin:0;padding:0px;width:100%;height:100%;background-color:#FFFFFF;">

    <div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
      HEADER
    </div>
    <div style="width:1024px;margin:0 auto;height:568px;background-color:#f0f0f0;text-align:center;">
      <form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
        Search:<input type="text" name="str" id="str">
        <input type="submit" value="send" name="send" id="send">
      </form>
      <div id="search_results"></div>
    </div>
    <div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
      FOOTER
    </div>

  </body>

</html>
 
db_query.php
 
<?php

define("HOST", "localhost");

// Database user
define("DBUSER", "username");

// Database password
define("PASS", "password");

// Database name
define("DB", "database_name");

// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');

############## Make the mysql connection ###########

$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);

$db = mysql_select_db(DB) or die(DB_MSG_ERROR);


$query = mysql_query("
  SELECT * 
  FROM persons 
  WHERE age='".$_POST['value']."'
");

echo '<table>';

while ($data = mysql_fetch_array($query)) {

  echo '
  <tr style="background-color:pink;">
    <td style="font-size:18px;">'.$data["name"].'</td>
    <td style="font-size:18px;">'.$data["age"].'</td>
  </tr>';

}

echo '</table>';

?> 


Thursday, November 21, 2013

Storing the Total Number of times a Page is viewed

A quick one on how to do a page view count on your site using php.
The code below can be manipulated to achieve other objective depending on your level of understanding on how the code works, it is straight to the point, all you need do is to create a database e.g named PageView  using PhpMyAdmin and run the SQL below to generate your table the create a new php page and insert the code PHP bellow that is all. run the the page and see what happened and also refresh PhpMyAdmin and see the inserted records including the page URL itself.
if this information do help you do remember to leave a comment or subscribe for more. 
SQL:

REATE TABLE IF NOT EXISTS `views` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `page` varchar(150) NOT NULL,
  `datetime` datetime NOT NULL,
  `newsid` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=28 ;

PHP
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_conn = "localhost";
$database_conn = "
PageView";
$username_conn = "root";
$password_conn = "root";
$conn = mysql_connect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
?>


<?php
if (isset($_SERVER["SCRIPT_NAME"])){
mysql_select_db($database_conn, $conn);
$query2 = "INSERT INTO views (page, datetime,newsid) VALUES ('".$_SERVER["SCRIPT_NAME"]."', CURDATE(), '$_SESSION[newsid]')";
$result2 = mysql_query($query2,$conn);

$query3="SELECT COUNT(*) as total FROM views WHERE newsid='$_GET[newsid]'";
$result3=mysql_query($query3,$conn);
while($data=mysql_fetch_array($result3)){
    $count = $data['total'];
}
}

 echo $count;
?>

Wednesday, November 20, 2013

Multiple Drop-Down Select Lists Creator

Multiple Select Dropdown List with AJAX

This tutorial presents an AJAX script that can be used to create dynamically multiple Select lists with data from a MySQL table.

First, a single select list is displayed on the page, then when the user chooses an option, it calls an Ajax function that acceses a PHP file that will return a select list according to the option selected. The Ajax function receives and displays the second select list.
When the users selects an option from the second select list, this script can display a third list of options, according to the options selected in the first an second select lists.

The script contains two files, a PHP file (named "select_list.php") with the code that selects data from a MySQL table and returns a select drop down list, and a JS file (named "ajax_select.js") with the Ajax code that accesses the PHP file.
You can copy and use the code for these files displayed below, or download the files from: Script Multiple Select Dropdown List

Check out this resource: http://coursesweb.net/scripts/select_lists_creator/create_select_lists.html