Archive for the ‘MySQL’ Category

In working on my new site layout, one thing I was wanting is when there are a lot of results (read, pictures in a particular gallery), is to split the results up into pages. Currently I just have it set to 12 pictures (and the pictures go 4 wide), so after 3 rows, I wanted it to have a link to a new page. I also wanted links to each individual page (this may change in the future when there are too many pictures in one gallery and there ends up being 30 some odd pages, but I will change it when it happens).

So to start out, I will assume you already have some basic things set up with your php document. One would be the correct variables passed through the address bar, another is a database setup with enough rows to have enough results to go into multiple pages.

So we first need to start with an sql query to find out how many results we will be dealing with. This gets us one of the primary numbers we need to start the calculations. In my db, I have a pic table that list all the info for all the pictures with a cell for it to link to the album table. In my address bar it passes the album id, which I then store in the $album variable.

// Specify the maximum amount of results per page, you could add a drop down box where the end-user
// can change it themselves
$max_pics=12;
 
// Pretty straightforward mysql query
$sql="SELECT count(id) AS count FROM pic WHERE album=$album";
$result=mysql_query($sql);
$pic_count=mysql_fetch_assoc($result);
 
// This is part of the magic. First thing we do is take the amount of results returned ($pic_count['count'])
// and then we divide it by the maximum amount of pics allowed per page.
 
// Then we run the ceil function on the result which will round the answer up to the next whole number.
// This will give us the total number of pages that all the results will take.
$total_pages=ceil($pic_count['count']/$max_pics);

So the above gets us a starting point with the total amount of pages that will display with the results and the maximum number of results we want on a page. The next process is to get the page number that we are currently on. Currently I am just doing this with a $_GET from the address bar (so the address would read index.php?page=2), but I may choose to redo this in the future to be more Search Engine Friendly.

We first need to do some error checking

// Check to make sure a page was passed and it is a number, if not set the page to the first one
if (isset($_GET['page']) && is_numeric($_GET['page']))
	$cur_page=$_GET['page'];
else
	$cur_page=1;
 
// Now we need to verify that the page is within the range of pages that we have, if not set to the first one
if ($cur_page < 1 || $cur_page > $total_page)
	$cur_page=1;

Now we need the mysql query that will get us just the results we want for the page. My query is pretty long, so I will be just putting in a simple query that will get you the results you need.

// First we need to get the starting result id, this is simply done by getting the current page minus one
// and then multiplying that by the maximum results you chose.
$start_result = ($cur_page - 1) * $max_pics;
 
// Next comes the actual query
$sql="SELECT * FROM pic WHERE album=$album LIMIT $start_pic, $max_pics";
$result=mysql_query($sql);

Now we need the html code to display the pages and the links to the pages. I haven’t done much in the way of css or making it look nice, but it is still functional.

// First display the mandatory html, along with the current page, and how many total pages there are
echo '
<div class="page_list>
	<p class="show_page">
		Page: ' . $cur_page . ' of ' . $total_page . '
	</p>';
 
// Now if there is more than one page create the links for the other pages
if ($total_page > 1)
{
	echo '
	<p class="page_links">';
 
// Give the first page to start counting to display all the pages upto the total pages
	$page_count = 1;
	while ( $page_count <= $total_page )
	{
 
// Check and see if the page link being created is the current page, because we don't need a link to the
// current page
		if ( $page_count == $curr_page )
		{
			echo '
			<span style="font-weight: bold;">' . $page_count . '</span>';
		}
 
// Otherwise create the links for the additional pages and point them back to the current php page
// Make sure you pass all the needed variables that were passed initially
		else
		{
			echo '
			<a href="' . $_SERVER['PHP_SELF'] . '?id=' . $album . '&amp;page=' . $page_count . '">
				' . $page_count . '
			</a>';
		}
 
// Up the $page_count for the while statement and then close the while statement
	$page_count++;
	}
 
// Echo the closing p tag then close the if statement for if there is more than one page
	echo '
		</p>
';
}
 
// Then close the div for the page info
echo '
</div>
';

I think that is all of the pertinent code out of my page. I will look over this when I get home so I can check and verify this all works properly. Hopefully I won’t have to make any changes.

It has been a little while since I made an entry, but there is good reason for that. I have been hard at work redesigning my Gallery layout for my picture galleries on My Air Force Life. The main thing I have been pushing for was integration into MySQL. There are obvious benefits of switching to that rather than just having static pages, but that is not the point of this entry.

The reason for this entry is to show how I did the little counter at the bottom of the pages. You know the ones…

Page created in x.xxx seconds with X queries.

Well I was wanting to figure out how to get this to work on my site. Part of the reason, is I am using my laptop as a testbed, so I want to see how resource intensive some of my queries may be. This is my first time actually developing something with MySQL, rather than editing existing code, and I wasn’t sure that my queries were going to be all that resource friendly.

Well to start since I will be doing many different queries on many different pages, I felt that I needed to create a function in a separate file that I would just include on my other files. I called the file func.query_time.php

Within that file, I had two separate functions. One which will time the query, add it to the total time, and add the amount of queries. The second function is just to display the actual info at the bottom of the pages. I will go through these functions separately, so people understand how they work. But I will have everything all together at the bottom.

So to start out we need to declare the function and we are calling it query.

function query($sql, $querycount, $totaltime)
{
   if (empty($querycount))
      $querycount=0;
 
   if (empty($totaltime))
      $totaltime=0;

All this does is recieve the query ($sql) and the querycount and totaltime amounts. And if the latter two were not passed when the function was called then it automatically sets them at zero. Next we need to get the time it takes to process the query.

   list($usec, $sec) = explode(' ',microtime());
   $querytime_before = ((float)$usec + (float)$sec);
 
   // run the query
   $result = mysql_query($sql);
 
   list($usec, $sec) = explode(' ',microtime());
   $querytime_after = ((float)$usec + (float)$sec);

The first part grabs the time before the query was run and stores it in $querytime_before. Then we actually run the MySQL query, then we get the time again and store it in $querytime_after. Now we need to get the totals of everything.

   $querytime = $querytime_after - $querytime_before;
   $totaltime += $querytime;
 
   $querycount++;

The first line take the time before and subtracts it from the time after which gives us the time it takes to make that query. Then we add the $querytime to $totaltime (the += is for adding another variable to the one it will be stored in ie. $totaltime = $totaltime + $querytime;). The last line is to add 1 to the querycount. The final part of this function is to return the info so you can use it on your regular page.

   return array($result, $querycount, $totaltime);
}

This returns the results back into the orginal file and closes out the function. Now onto the file itself and how you call the query.

Now the first time you call the function “query” there will be no variables set for $querycount or $totaltime, so you can just leave those out, but those variables will be returned. And since they are returned in an array there are a couple of ways to get them out. I prefer the list() function as it is simple and you can name the variables however you want.

   "sql = SELECT * FROM database";
   list($result, $querycount, $totaltime) = query($sql);

So the $sql query we have stored above is being passed to the function on the right, and then it runs through the function and returns us our info. On the second query it is only slightly different.

   $sql = "SELECT * FROM database WHERE id = 1";
   list($result2, $querycount, $totaltime) = query($sql, $querycount, $totaltime);

In this one we need to pass the $querycount and the $totaltime to the function. Otherwise it won’t know the numbers. Also note that you should change the variable for the MySQL query result depending on how your page is setup.

Now we have the displaying of the info. In the func.query_time.php file I had a second function declared. This function is small enough I won’t break it down.

function display_time($querycount, $totaltime)
{
   $strQueryTime = 'Page created in %01.4f seconds';
   echo '<p class="querytime">' . sprintf($strQueryTime, $totaltime) . ' with ' . $querycount . ' queries.</p>
}

So the function gets the querycount and totaltime variables passed to it. Then we store the string for the page created in x seconds into $strQueryTime. The %01.4f is used to shorten up the totaltime. Right now it will pad any unused spaces with 0′s and will go four decimal places to the right. We then use the sprintf function to display that with the totaltime added in and then the total number of queries that were counted. All that is left to do is show that on the page. This is done with

display_time ($querycount, $totaltime);

Now to show it all together. First the php file followed by the function file.

<?php
  require_once('func.query_time.php');
 
  $sql="SELECT * FROM database";
  list($result, $querycount, $totaltime)=query($sql);
 
  $sql="SELECT * FROM database WHERE id='1'";
  list($result2, $querycount, $totaltime)=query($sql, $querycount, $totaltime);
 
  display_time($querycount, $totaltime);
?>
<?php
 
function query($sql, $querycount, $totaltime)
{
 
  if(empty($querycount))
    $querycount=0;
 
  if(empty($totaltime))
    $totaltime=0;
 
  list($usec, $sec) = explode(' ',microtime());
  $querytime_before = ((float)$usec + (float)$sec);
 
  $result=mysql_query($sql);
 
  list($usec, $sec) = explode(' ',microtime());
  $querytime_after = ((float)$usec + (float)$sec);
 
  $querytime = $querytime_after - $querytime_before;
 
  $totaltime += $querytime;
 
  $querycount++;
 
  return array($result, $querycount, $totaltime);
}
 
function display_time($querycount, $totaltime)
{
 
  $strQueryTime = 'Page created in %01.4f seconds';
 
  echo '<p class="querytime">' . sprintf($strQueryTime, $totaltime) . ' with ' . $querycount . ' queries.</p>';
}
 
?>

So there you have it. Any questions or things you believe I could do better, let me know in the comments. And I am sure that there will be more code that I will post before the gallery overhaul is complete. Stay tuned…

I recently read a blog post on the How-To Geek about setting up OpenDNS and the options it gives you to secure your internet browsing. They have quite a few filtering options including Phishing sites, along with blocking adult-related sites, and about 50 other categories along with a fully redundant DNS nameserver resolving. I decided to try it and set it up on my home network. The problem is that if you have an internet provider that provides you with a dynamic IP (IP address changes occasionally, if you aren’t sure what you have you probably have a dynamic address), you need to update the IP with OpenDNS. They have a lot of clients out there to do it, but as far as I found there were no linux clients. So I created a short linux script to do just that.

[lang='bash']#!/bin/bash

# Copyright (C) 2006 Jeremy Brent Hansen
#
# These are for your OpenDNS username and password. At this time, I do
# not know how to hide this info, so you will need to make sure you have the
# correct file permissions.
username=your_opendns_username
passwd=your_opendns_password

# This is where the log file will be stored. Currently it only logs the current IP
# and the response back from OpenDNS. The log will keep one backup. I
# just used a folder in my home directory (make sure the folder exists).
log_dir=~/.opendns

# Revolves the log file. Keeps one backup.
mv $log_dir/log $log_dir/log.1

while [ 1 ]
do

date >> $log_dir/log
/usr/bin/curl -i -m 60 -k -u $username:$passwd ‘https://updates.opendns.com/account/ddns.php?’ -silent >> $log_dir/log
echo -e “\n” >> $log_dir/log

# Resends the info after 5 minutes. Eventually I plan on changing it,

# so it only updates when your IP changes.
sleep 600

done[/lang]

So, there you have it. No root permissions are required, so I just have it in my .profile for my normal user. Just run it with the & at the end, so it will background the process.