<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Snipe.Net &#187; mysql</title>
	<atom:link href="http://www.snipe.net/tags/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.snipe.net</link>
	<description>Bitterness never tasted so sweet</description>
	<lastBuildDate>Thu, 29 Jul 2010 05:03:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Using IP Geolocation and Radius Searching with PHP/MySQL</title>
		<link>http://www.snipe.net/2008/12/ip-geolocation-radius-search-in-php/</link>
		<comments>http://www.snipe.net/2008/12/ip-geolocation-radius-search-in-php/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 19:05:50 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[geolocation]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web dev]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=538</guid>
		<description><![CDATA[Delivering content relative to the physical location of your users is an excellent (and fairly easy) way to fine-tune the content you&#8217;re delivering to be most relevent to the people visiting your site. Two simple ways of doing this are to use an IP-based geolocation lookup, or to do a manual radius search (like a [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2008%2F12%2Fip-geolocation-radius-search-in-php%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2008%2F12%2Fip-geolocation-radius-search-in-php%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<p>Delivering content relative to the physical location of your users is an excellent (and fairly easy) way to fine-tune the content you&#8217;re delivering to be most relevent to the people visiting your site. Two simple ways of doing this are to use an IP-based geolocation lookup, or to do a manual radius search (like a &#8220;store finder&#8221; type of functionality), where the user manually enters a postal code. Both function on the same logic &#8211; the real difference is that one requires a third-party service that can fetch the user&#8217;s latitude and longitude based on IP address. This functionality can be used to show content such as local news, local store branches, etc &#8211; as soon as the user visits your page.</p>
<p><span id="more-538"></span></p>
<p>The nuts and bolts of IP-based geolocation is as follows:</p>
<ol>
<li>User lands on the web page</li>
<li>User&#8217;s IP is captured and posted to a third-party geolocation service, which returns a latitude and longitude for the IP address</li>
<li>Website performs a radius database search using the latitude and longitude provided by the third party service and returns content relative to that location</li>
</ol>
<p>Bear in mind, your database must contain data that is stored with a latitude and longitude for this to work. You cannot compare a user&#8217;s latitude and longitude to the lat/long of a piece of data if you have no lat/long associated to your content.</p>
<p>Also, please note: the services mentioned here &#8211; and the code provided &#8211; is intended for US-based geolocation. The code will remain basically the same for non-US lookups, but you may need to use alternate third-party services if your country is not covered by the ones mentioned here.</p>
<h2>1. Getting Latitude/Longitude for Your Database Data</h2>
<p>The first part of this process starts with you tagging your existing or newly added database data with the correct latitude and longitude. Each item you wish to include in the radius search should have a valid lat/long value in the latitude and longitude fields. If you are modifying an existing database, you would execute an alter table command to add the new lat/long fields. For this example, we&#8217;ll be using a table called stores:</p>
<pre class="brush: sql">CREATE TABLE `stores` (
`store_id` INT NOT NULL AUTO_INCREMENT ,
`store_address` VARCHAR( 40 ) NULL ,
`store_city` VARCHAR( 40 ) NULL ,
`store_state` VARCHAR( 2 ) NULL ,
`store_country` VARCHAR( 2 ) NULL ,
`store_phone` VARCHAR( 15 ) NULL ,
UNIQUE (`store_id`));</pre>
<p>And then we add the new latitude and longitude fields to our stores table, using the DOUBLE datatype:</p>
<pre class="brush: sql">ALTER TABLE `stores` ADD `latitude` DOUBLE NULL ,
ADD `longitude` DOUBLE NULL ;</pre>
<p>Now our table is set up to store the latitude and longitude data, but from where do we actually get the data, short of manually looking it up for each row of data in our stores table?  Easy. There is a fabulous free service available at <a href="http://rpc.geocoder.us/" target="_blank">rpc.geocoder.us</a> that lets you post an address to their API, to which it responds with the latitude and longitude values for that address. The easiest way to handle this process is to set up a cURL request in the admin area where you&#8217;re managing your data &#8211; otherwise you&#8217;ll need to write a script to cycle through the rows of data, fetching the latitude and longitude.(You will, of course, need to have PHP configured with cURL support for this to work.) Using this service, free lookups are throttled by your IP address to one request every 15 seconds &#8211; this may cause issues when you&#8217;re initially trying to get the lat/long data into your database for existing records, but shouldn&#8217;t be much of an issue afterwards.</p>
<p>First let&#8217;s set up a small function to handle the cURL request:</p>
<pre class="brush: php">function curl_string ($url){
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
$result = curl_exec ($ch);
curl_close($ch);
return $result;
</pre>
<p>The format you will be sending the query to the rpc.geocoder.us API is: <span class="linkification-ext"><a class="linkification-ext" title="Linkification: http://rpc.geocoder.us/service/csv?address=1600+Pennsylvania+Ave%2C+Washington+DC" href="http://rpc.geocoder.us/service/csv?address=1600+Pennsylvania+Ave%2C+Washington+DC">http://rpc.geocoder.us/service/csv?address=1600+Pennsylvania+Ave%2C+Washington+DC</a></span></p>
<pre class="brush: php">
// set the url of the API using the address, city and state we want to query

$url_page = &quot;http://&quot;.&quot;rpc.&quot;.&quot;.geocoder&quot;.&quot;.us/service/csv&quot;;
$url_page .=&quot;?address=&quot;.urlencode($address).&quot;,&quot;.urlencode($city).&quot;,&quot;.$state;

// execute the cURL request
$string = curl_string($url_page);

// turn the comma separated csv data turned into an array,
// so we can easily see that a match was found and use the pieces
$address_pieces= explode(&quot;,&quot;, $string);

// make sure the array contains data
if (count($address_pieces) &gt; 0) {

// update the database
$sql = &quot;update stores set latitude=&#039;&quot;.$address_pieces[0].&quot;&#039;, &quot;;
$sql .=&quot;longitude=&#039;&quot;.$address_pieces[1].&quot;&#039;, &quot;;
$sql .=&quot;zip=&#039;&quot;.$address_pieces[5].&quot;&#039; where id=&#039;&quot;.$store_id.&quot;&#039;&quot;;

if ($update_latlong = mysql_query($sql)) {
echo &#039;Lat/long updated!&#039;;
} else {
// if the query failed, print out an error
echo mysql_error();
}

// if the array does not contain data, no match was found in geocoder.us, so suggest using google maps to find the lat/long manually
} else {
echo &#039;No geolocation match.&#039;;

}</pre>
<p>The code above will help you update your existing data if you were to use it in a script that cycles through your database records, or you can use it as part of your store administration area, doing the cURL request every time a new store is saved to the database.</p>
<h2>2. Getting the Latitude and Longitude of the User</h2>
<p>Now that you have base lat/long data for the data in your database, you have to obtain the lat/long for the user visiting the site. For this next part, you will again need to access a third-party service, this time to get the latitude and longitude based on the user&#8217;s IP address. I use a commercial service available from <a href="http://www.maxmind.com/app/city" target="_blank">MaxMind.Com</a>. It&#8217;s not free, but their prices are very reasonable ($20 per 50,000 queries) &#8211; and by using a cookie to store whether or not the user&#8217;s lat/long has already been returned, you can save on the number of accesses you use up on a busy site.</p>
<pre class="brush: php">// begin the session
session_start();

$expireTime = 60*60*24*30; // 30 days
session_set_cookie_params($expireTime);

if ((!isset($_SESSION[&#039;geo_country&#039;])) || ($_SESSION[&#039;geo_country&#039;]==&#039;&#039;))    {

// enter your MaxMind license key here
$license_key=&#039;XXXXXXXXXXXXXXX&#039;;
$ip = $_SERVER[&#039;REMOTE_ADDR&#039;];

$query = &quot;http://&quot;.&quot;geoip1.&quot;.&quot;maxmind&quot;.&quot;.com/b?l=&quot; . $license_key . &quot;&amp;amp;amp;amp;amp;amp;amp;amp;amp;i=&quot; . $ip;
$url = parse_url($query);
$host = $url[&quot;host&quot;];
$path = $url[&quot;path&quot;] . &quot;?&quot; . $url[&quot;query&quot;];
$timeout = 1;
$fp = fsockopen ($host, 80, $errno, $errstr, $timeout)
or die(&#039;Can not open connection to server.&#039;);

if ($fp) {
fputs ($fp, &quot;GET $path HTTP/1.0\nHost: &quot; . $host . &quot;\n\n&quot;);

while (!feof($fp)) {
$buf .= fgets($fp, 128);
} // endwhile

// split the output into an array
$lines = split(&quot;\n&quot;, $buf);
$data = $lines[count($lines)-1];
fclose($fp);

$geo = explode(&quot;,&quot;,$data);
$user_geo_country = $geo[0];
$user_geo_state = $geo[1];
$user_geo_city = $geo[2];
$user_geo_lat = $geo[3];
$user_geo_lon = $geo[4];

$_SESSION[&#039;geo_country&#039;] = $user_geo_country;
$_SESSION[&#039;geo_state&#039;] = $user_geo_state;
$_SESSION[&#039;geo_city&#039;] = $user_geo_city;
$_SESSION[&#039;geo_lat&#039;] = $user_geo_lat;
$_SESSION[&#039;geo_lon&#039;] = $user_geo_lon;

setcookie(&quot;geolocCookieCountry&quot;, $user_geo_country, time()+$expireTime, &quot;/&quot;);
setcookie(&quot;geolocCookieCity&quot;, $user_geo_city, time()+$expireTime, &quot;/&quot;);
setcookie(&quot;geolocCookieState&quot;, $user_geo_state, time()+$expireTime, &quot;/&quot;);
setcookie(&quot;geolocCookieLat&quot;, $user_geo_lat, time()+$expireTime, &quot;/&quot;);
setcookie(&quot;geolocCookieLon&quot;, $user_geo_lon, time()+$expireTime, &quot;/&quot;);

} // endif $fp

} // endif session set
</pre>
<p>Now, you&#8217;ll only be querying MaxMind if the user hasn&#8217;t already accessed the site before and had their latitude and longtude stored in the cookie. Note the $license variable in the code above. When you sign up for the MaxMind Web Service, you will be given a license number, which you&#8217;ll insert there.</p>
<h2>3. Putting the Two Together to Return Results Within X Miles</h2>
<p>To tie the two together and query the database, returning only results that are within a specified number of miles of the user&#8217;s IP address, we&#8217;ll need two classes:</p>
<pre class="brush: php">class RadiusCheck {

var $maxLat;
var $minLat;
var $maxLong;
var $minLong;

function RadiusCheck($Latitude, $Longitude, $Miles) {
global $maxLat,$minLat,$maxLong,$minLong;
$EQUATOR_LAT_MILE = 69.172;
$maxLat = $Latitude + $Miles / $EQUATOR_LAT_MILE;
$minLat = $Latitude - ($maxLat - $Latitude);
$maxLong = $Longitude + $Miles / (cos($minLat * M_PI / 180) * $EQUATOR_LAT_MILE);
$minLong = $Longitude - ($maxLong - $Longitude);
}

function MaxLatitude() {
return $GLOBALS[&quot;maxLat&quot;];
}
function MinLatitude() {
return $GLOBALS[&quot;minLat&quot;];
}
function MaxLongitude() {
return $GLOBALS[&quot;maxLong&quot;];
}
function MinLongitude() {
return $GLOBALS[&quot;minLong&quot;];
}

}</pre>
<p>and</p>
<pre class="brush: php">class DistanceCheck {

function DistanceCheck() {
}

function Calculate(
$dblLat1,
$dblLong1,
$dblLat2,
$dblLong2
) {
$EARTH_RADIUS_MILES = 3963;
$dist = 0;

//convert degrees to radians
$dblLat1 = $dblLat1 * M_PI / 180;
$dblLong1 = $dblLong1 * M_PI / 180;
$dblLat2 = $dblLat2 * M_PI / 180;
$dblLong2 = $dblLong2 * M_PI / 180;

if ($dblLat1 != $dblLat2 || $dblLong1 != $dblLong2)
{
//the two points are not the same
$dist =
sin($dblLat1) * sin($dblLat2)
+ cos($dblLat1) * cos($dblLat2)
* cos($dblLong2 - $dblLong1);

$dist =
$EARTH_RADIUS_MILES
* (-1 * atan($dist / sqrt(1 - $dist * $dist)) + M_PI / 2);
}
return $dist;
}

}</pre>
<p>And then, to perform the actual query:</p>
<pre class="brush: php">
// set a default number of miles to search within
$Miles = &#039;50&#039;;

// set the user&#039;s latitude and longitude as the one to search against
$Latitude = $user_geo_lat;
$Longitude = $user_geo_lon;

$zcdRadius = new RadiusCheck($Latitude,$Longitude,$Miles);
$minLat = $zcdRadius-&gt;MinLatitude();
$maxLat = $zcdRadius-&gt;MaxLatitude();
$minLong = $zcdRadius-&gt;MinLongitude();
$maxLong = $zcdRadius-&gt;MaxLongitude();

$sql = &quot;SELECT store_address, store_city, store_state, store_phone, &quot;;
$sql .= &quot;SQRT((((69.1*(latitude-$Latitude))*(69.1*(latitude-$Latitude)))+((53*(longitude-$Longitude))*(53*(longitude-$Longitude))))) &quot;;
$sql .= &quot;AS calc FROM stores where  &quot;;
$sql .= &quot;latitude &gt;= &#039;$minLat&#039; &quot;;
$sql .= &quot;AND latitude &lt;= &#039;$maxLat&#039; &quot;;
$sql .= &quot;AND longitude &gt;= &#039;$minLong&#039; &quot;;
$sql .= &quot;AND longitude &lt;= &#039;$maxLong&#039; &quot;;
$get_data = mysql_query($sql);

// loop through the matching database results
while($storedata = mysql_fetch_assoc($get_data)) {

// calculate the number of miles away the result is
$zcdDistance = new DistanceCheck;
$Distance = $zcdDistance-&gt;Calculate($Latitude,$Longitude,$storedata[&#039;latitude&#039;],$storedata[&#039;longitude&#039;]);

// and for the non-US people, here&#039;s the km calculation
$calc_km = round(($Distance * 1.609344),2);

echo &#039;&lt;li&gt;&#039;.$storedata[&#039;store_address&#039;].&#039;&lt;br /&gt;&#039;.$storedata[&#039;store_city&#039;].&#039;, &#039;;
echo $storedata[&#039;store_state&#039;].&#039; &#039;.$storedata[&#039;store_country&#039;].&#039;&lt;br /&gt;&#039;;
echo $storedata[&#039;store_phone&#039;].&#039;&lt;br /&gt;&#039;;
echo &#039;Distance: &#039;.$Distance.&#039; (&#039;.$calc_km.&#039; km)&#039;;
}</pre>
<p>And that&#8217;s really all there is to it.</p>
<h2>Store Locator Only</h2>
<p>If you want to create a store-locator style script without automagically getting the user&#8217;s current location, you&#8217;d use the code above, almost verbatim. The difference is that you&#8217;d need an additional table of zipcodes with associated lat/long, available for purchase (again, not very expensive) from <a href="http://www.zipcodedownload.com/" target="_blank">ZipCodeDownload.Com</a>. The process would go as follows:</p>
<ol>
<li>User arrives at your site, and enters a zip code and mile radius they wish to search using your search form &#8211; clicks submit</li>
<li>The script queries the zip code table to find the latitude and longitude associated with the postal code the user has entered, and uses THAT latitude and longitude as the values for $Latitude and $Longitude in the code above, and uses the user-entered values for $Miles from the search form.</li>
</ol>
<p>Everything else stays exactly the same. Naturally, you&#8217;ll probably want to add some sanity checks in your own code (gracefully displaying default content if no latitude and longitude is returned, etc) but I decided to skip that here so as not to confuse anyone.</p>
<p>Enjoy, and if you end up using this anywhere, let me know how it works out.</p>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2002/06/alternating-row-colors-in-phpmysql/' rel='bookmark' title='Permanent Link: Alternating Row Colors in PHP/mySQL'>Alternating Row Colors in PHP/mySQL</a> <small>Using alternating row colors in a PHP database application is...</small></li>
<li><a href='http://www.snipe.net/2006/06/creating-a-multi-level-listbox-in-phpmysql/' rel='bookmark' title='Permanent Link: Creating a Multi-Level Listbox in PHP/mySQL'>Creating a Multi-Level Listbox in PHP/mySQL</a> <small>This lets you create a nested multi-level category menu through...</small></li>
<li><a href='http://www.snipe.net/2002/06/phpmysql-breadcrumb-trail/' rel='bookmark' title='Permanent Link: PHP/mySQL Breadcrumb Trail'>PHP/mySQL Breadcrumb Trail</a> <small>This lets you automatically create a breadcrumb trail navigation through...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2008/12/ip-geolocation-radius-search-in-php/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Identify and Fix SQL Injection Vulnerabilities in Web Applications</title>
		<link>http://www.snipe.net/2008/07/identify-and-fix-sql-injection-vulnerabilities-in-web-applications/</link>
		<comments>http://www.snipe.net/2008/07/identify-and-fix-sql-injection-vulnerabilities-in-web-applications/#comments</comments>
		<pubDate>Tue, 01 Jul 2008 16:15:34 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Windows Downloads]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[freeware]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=157</guid>
		<description><![CDATA[Scrawlr is a free software for scanning SQL injection vulnerabilities on your web applications, developed by HP Web Security Research Group in coordination with Microsoft Security Response Center. Scrawlr crawls a website while simultaneously analyzing the parameters of each individual web page for SQL Injection vulnerabilities. After the scanning process, if it can find vulnerabilities, [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2008%2F07%2Fidentify-and-fix-sql-injection-vulnerabilities-in-web-applications%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2008%2F07%2Fidentify-and-fix-sql-injection-vulnerabilities-in-web-applications%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<p>Scrawlr is a free software for scanning SQL injection vulnerabilities on your web applications, developed by HP Web Security Research Group in coordination with Microsoft Security Response Center.</p>
<p><span id="more-157"></span></p>
<p><a href="http://www.snipe.net/wp-content/uploads/2008/07/screenshot.jpg"><img class="aligncenter size-full wp-image-156" title="screenshot" src="http://www.snipe.net/wp-content/uploads/2008/07/screenshot.jpg" alt="" width="400" height="308" /></a></p>
<p>Scrawlr crawls a website while simultaneously analyzing the parameters of each individual web page for SQL Injection vulnerabilities.</p>
<p>After the scanning process, if it can find vulnerabilities, it will display your database table names as a proof of the possible SQL injection vulnerabilities.</p>
<p>From the <a href="http://www.communities.hp.com/securitysoftware/blogs/spilabs/archive/2008/06/23/finding-sql-injection-with-scrawlr.aspx" target="_blank">HP Scrawlr website</a>:</p>
<blockquote><p><strong>Technical details for Scrawlr</strong></p>
<ul>
<li>Identify Verbose SQL Injection vulnerabilities in URL parameters</li>
<li>Can be configured to use a Proxy to access the web site</li>
<li>Will identify the type of SQL server in use</li>
<li>Will extract table names (verbose only) to guarantee no false positives</li>
</ul>
<p>Scrawlr does have some limitations versus our professional solutions and our fully functional SQL Injector tool</p>
<ul>
<li>Will only crawls up to 1500 pages</li>
<li>Does not support sites requiring authentication</li>
<li>Does not perform Blind SQL injection</li>
<li>Cannot retrieve database contents</li>
<li>Does not support JavaScript or flash parsing</li>
<li>Will not test forms for SQL Injection (POST Parameters)</li>
</ul>
</blockquote>
<p>There are some limitations, as noted in the above bulleted list, however this is certainly a good start to help web developers find and correct vulnerabilities in their applications. <a href="https://download.spidynamics.com/Products/scrawlr/" target="_blank">Download Scrawlr now</a> &#8211; Windows Only.</p>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2008/07/generate-lists-of-banned-words-for-forums-and-other-applications/' rel='bookmark' title='Permanent Link: Generate lists of banned words for forums and other applications'>Generate lists of banned words for forums and other applications</a> <small>If you develop software for a living, or if you...</small></li>
<li><a href='http://www.snipe.net/2009/01/advertising-on-facebook-applications-an-experiment/' rel='bookmark' title='Permanent Link: Advertising on Facebook Applications &#8211; An Experiment'>Advertising on Facebook Applications &#8211; An Experiment</a> <small>This article has been deprecated, and has been replaced by...</small></li>
<li><a href='http://www.snipe.net/2002/06/alternating-row-colors-in-phpmysql/' rel='bookmark' title='Permanent Link: Alternating Row Colors in PHP/mySQL'>Alternating Row Colors in PHP/mySQL</a> <small>Using alternating row colors in a PHP database application is...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2008/07/identify-and-fix-sql-injection-vulnerabilities-in-web-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Multi-Level Listbox in PHP/mySQL</title>
		<link>http://www.snipe.net/2006/06/creating-a-multi-level-listbox-in-phpmysql/</link>
		<comments>http://www.snipe.net/2006/06/creating-a-multi-level-listbox-in-phpmysql/#comments</comments>
		<pubDate>Mon, 19 Jun 2006 16:11:10 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=32</guid>
		<description><![CDATA[This lets you create a nested multi-level category menu through PHP and mySQL. Using a recursive function, we can display an unlimited number of nested categories, for a drop down box that might look like this: Fruit &#8211; Apples &#8212;->Red Delicious &#8212;->Granny Smith Database: This code is assuming that you have a database table containing [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2006%2F06%2Fcreating-a-multi-level-listbox-in-phpmysql%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2006%2F06%2Fcreating-a-multi-level-listbox-in-phpmysql%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<p>This lets you create a nested multi-level category menu through PHP and mySQL. Using a recursive function, we can display an unlimited number of nested categories, for a drop down box that might look like this:</p>
<p>Fruit<br />
&#8211; Apples<br />
&#8212;->Red Delicious<br />
&#8212;->Granny Smith</p>
<p><span id="more-32"></span></p>
<p><strong>Database:</strong><br />
This code is assuming that you have a database table containing your menu options that looks something like this:</p>
<pre>Table categories:
+--------+----------------------+-----------+
| id         | name                                 | parent_id |
+--------+----------------------+-----------+
|           0 | Main Category 1           | 0                 |
|           1 | Main category 2           | 0                 |
|           2 | Subcategory 1               | 1                 |
|           3 | Subcategory 2               | 1                 |
|           4 | Main category 3           | 0                 |
+--------+----------------------+-----------+</pre>
<p>It is also assuming that the name of your listbox is &#8220;cat_id&#8221;. This is easily changed, mind you &#8211; you just have to change the select code down at the bottom and the &#8220;$categories = $_POST['cat_id'];&#8221; line to reflect whatever you&#8217;re naming it.</p>
<pre class="brush: php">// $current_cat_id: the current category id number
// $count: just a counter, call it as 0 in your function call and forget about it
/* GET THE DROP DOWN LIST OF CATEGORIES */

function get_cat_selectlist($current_cat_id, $count) {

static $option_results;
// if there is no current category id set, start off at the top level (zero)
if (!isset($current_cat_id)) {
$current_cat_id =0;
}
// increment the counter by 1
$count = $count+1;

// query the database for the sub-categories of whatever the parent category is
$sql =  &#039;SELECT id, name from categories where parent_id =  &#039;.$current_cat_id;
$sql .=  &#039;order by name asc &#039;;

$get_options = mysql_query($sql);
$num_options = mysql_num_rows($get_options);

// our category is apparently valid, so go ahead €¦
if ($num_options &gt; 0) {
while (list($cat_id, $cat_name) = mysql_fetch_row($get_options)) {

// if its not a top-level category, indent it to
//show that its a child category

if ($current_cat_id!=0) {
$indent_flag =  &#039;--&#039;;
for ($x=2; $x&lt; =$count; $x++) {
$indent_flag .=  &#039; &gt;&#039;;
}
}
$cat_name = $indent_flag.$cat_name;
$option_results[$cat_id] = $cat_name;
// now call the function again, to recurse through the child categories
get_cat_selectlist($cat_id, $count );
}
}
return $option_results;
}</pre>
<p>You would call the function using something like this:</p>
<pre class="brush: php">
echo &#039;&lt;select name=&quot;cat_id&quot;&gt;&#039;;
echo &#039;&lt;option value=&quot;&quot;&gt;-- Select -- &lt;/option&gt;&#039;;

$get_options = get_cat_selectlist(0, 0);
if (count($get_options) &gt; 0){

$categories = $_POST[&#039;cat_id&#039;];
foreach ($get_options as $key =&gt; $value) {

$options .=&quot;&lt;option value=\&quot;$key\&quot;&quot;;

// show the selected items as selected in the listbox
if ($_POST[&#039;cat_id&#039;] == &quot;$key&quot;) {
$options .=&quot; selected=\&quot;selected\&quot;&quot;;
}
$options .=&quot;&gt;$value&lt;/option&gt;\n&quot;;
}
}
echo $options;

echo &#039;&lt;/select&gt;&#039;;</pre>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2002/06/phpmysql-breadcrumb-trail/' rel='bookmark' title='Permanent Link: PHP/mySQL Breadcrumb Trail'>PHP/mySQL Breadcrumb Trail</a> <small>This lets you automatically create a breadcrumb trail navigation through...</small></li>
<li><a href='http://www.snipe.net/2006/06/checkboxesmultiple-select-boxes-in-php/' rel='bookmark' title='Permanent Link: Checkboxes/Multiple Select Boxes in PHP'>Checkboxes/Multiple Select Boxes in PHP</a> <small>For the PHP newbie, checkboxes and/or multiple select listboxes can...</small></li>
<li><a href='http://www.snipe.net/2002/06/page-numbering-with-x-results-per-page/' rel='bookmark' title='Permanent Link: Page Numbering (with x results per page)'>Page Numbering (with x results per page)</a> <small>Although there are several examples of this type of code...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2006/06/creating-a-multi-level-listbox-in-phpmysql/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Dynamic thumbnailing with PHP and Imagemagick</title>
		<link>http://www.snipe.net/2004/06/dynamic-thumbnailing-with-php-and-imagemagick/</link>
		<comments>http://www.snipe.net/2004/06/dynamic-thumbnailing-with-php-and-imagemagick/#comments</comments>
		<pubDate>Sun, 27 Jun 2004 15:11:50 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[image manipulation]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=134</guid>
		<description><![CDATA[This code formatting is a little off, since the WYSIWG editor seems to have eaten part of it. Sorry. &#60;?php /* &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;- */ /* &#8212;&#8212;&#8212;&#8212; BEGIN PHP SNIPPET &#8212;&#8212;&#8212;&#8212;&#8212;-*/ /* &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;- */ // specify your file details $current_file = &#8220;image.jpg&#8221;; $max_width = &#8220;150&#8243;; // get the current info on the file $current_size = getimagesize($current_file); $current_img_width [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2004%2F06%2Fdynamic-thumbnailing-with-php-and-imagemagick%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2004%2F06%2Fdynamic-thumbnailing-with-php-and-imagemagick%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<p>This code formatting is a little off, since the WYSIWG editor seems to have eaten part of it. Sorry.</p>
<p><code><span style="color: #000000;"><span style="color: #0000bb;">&lt;?php</span></span></code></p>
<p><span style="color: #ff8000;">/* &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;- */<br />
/* &#8212;&#8212;&#8212;&#8212; BEGIN PHP SNIPPET &#8212;&#8212;&#8212;&#8212;&#8212;-*/<br />
/* &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;- */<br />
// specify your file details<br />
</span><span style="color: #0000bb;">$current_file </span><span style="color: #007700;">= </span><span style="color: #dd0000;">&#8220;image.jpg&#8221;</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$max_width </span><span style="color: #007700;">= </span><span style="color: #dd0000;">&#8220;150&#8243;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">// get the current info on the file<br />
</span><span style="color: #0000bb;">$current_size </span><span style="color: #007700;">= </span><span style="color: #0000bb;">getimagesize</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$current_file</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$current_img_width </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$current_size</span><span style="color: #007700;">[</span><span style="color: #0000bb;">0</span><span style="color: #007700;">];<br />
</span><span style="color: #0000bb;">$current_img_height </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$current_size</span><span style="color: #007700;">[</span><span style="color: #0000bb;">1</span><span style="color: #007700;">];<br />
</span><span style="color: #0000bb;">$image_base </span><span style="color: #007700;">= </span><span style="color: #0000bb;">explode</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8220;.&#8221;</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$current_file</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">// this part gets the new thumbnail name<br />
</span><span style="color: #0000bb;">$image_basename </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$image_base</span><span style="color: #007700;">[</span><span style="color: #0000bb;">0</span><span style="color: #007700;">];<br />
</span><span style="color: #0000bb;">$image_ext </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$image_base</span><span style="color: #007700;">[</span><span style="color: #0000bb;">1</span><span style="color: #007700;">];<br />
</span><span style="color: #0000bb;">$thumb_name </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$image_basename</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8220;-th.&#8221;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">$image_ext</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">// determine if the image actually needs to be resized<br />
// and if it does, get the new height for it<br />
</span><span style="color: #007700;">if (</span><span style="color: #0000bb;">$current_img_width </span><span style="color: #007700;">&gt; </span><span style="color: #0000bb;">$max_width</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$too_big_diff_ratio </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$current_img_width</span><span style="color: #007700;">/</span><span style="color: #0000bb;">$max_width</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$new_img_width </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$max_width</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$new_img_height </span><span style="color: #007700;">= </span><span style="color: #0000bb;">round</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$current_img_height</span><span style="color: #007700;">/</span><span style="color: #0000bb;">$too_big_diff_ratio</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">// presto chango alacazam<br />
</span><span style="color: #0000bb;">$make_magick </span><span style="color: #007700;">= </span><span style="color: #0000bb;">system</span><span style="color: #007700;">(</span><span style="color: #dd0000;">&#8220;convert -geometry $new_img_width x $new_img_height $current_file $thumb_name&#8221;</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$retval</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">// let us know if it worked or not<br />
</span><span style="color: #007700;">if (!(</span><span style="color: #0000bb;">$retval</span><span style="color: #007700;">)) {<br />
echo </span><span style="color: #dd0000;">&#8220;Thumbnail createdÂ Â -&#8221;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">$thumb_name</span><span style="color: #007700;">;<br />
} else {<br />
echo </span><span style="color: #dd0000;">&#8220;Oops &#8211; no dice! Script failed cuz your momma doesn&#8217;t love you.&#8221;</span><span style="color: #007700;">;<br />
}<br />
} else {<br />
echo </span><span style="color: #dd0000;">&#8220;No need to resize! You&#8217;re perfect just the way you are.&#8221;</span><span style="color: #007700;">;<br />
}</span></p>
<p><span style="color: #0000bb;">?&gt;</span></p>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2004/06/dynamic-thumbnailing-with-php-and-the-gd-library/' rel='bookmark' title='Permanent Link: Dynamic thumbnailing with PHP and the GD library'>Dynamic thumbnailing with PHP and the GD library</a> <small>Although there are loads of ways you can do this,...</small></li>
<li><a href='http://www.snipe.net/2004/06/dynamic-watermarkstext-overlay-on-images-in-php/' rel='bookmark' title='Permanent Link: Dynamic Watermarks/Text Overlay on Images in PHP'>Dynamic Watermarks/Text Overlay on Images in PHP</a> <small>This code can be useful for a number of things,...</small></li>
<li><a href='http://www.snipe.net/2009/10/mini-site-facebook-static-fbml/' rel='bookmark' title='Permanent Link: Extending Facebook Static FBML Tabs with Dynamic Content'>Extending Facebook Static FBML Tabs with Dynamic Content</a> <small>This tutorial walks you through how to use DynamicFBML to...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2004/06/dynamic-thumbnailing-with-php-and-imagemagick/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Style Page Numbering (with x per page and y page numbers displayed)</title>
		<link>http://www.snipe.net/2002/06/google-style-page-numbering-with-x-per-page-and-y-page-numbers-displayed/</link>
		<comments>http://www.snipe.net/2002/06/google-style-page-numbering-with-x-per-page-and-y-page-numbers-displayed/#comments</comments>
		<pubDate>Thu, 27 Jun 2002 15:04:52 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=132</guid>
		<description><![CDATA[With just a few modifications, we can create a piece of code that will not only give you x results per page with page numbers, but it will also allow you to specify how many page numbers should appear on the page at any time, much like Google.Â  (For example, if you have hundreds of [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Fgoogle-style-page-numbering-with-x-per-page-and-y-page-numbers-displayed%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Fgoogle-style-page-numbering-with-x-per-page-and-y-page-numbers-displayed%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<p>With just a few modifications, we can create a piece of code that will not only give you x results per page with page numbers, but it will also allow you to specify how many page numbers should appear on the page at any time, much like Google.Â  (For example, if you have hundreds of page numbers, this would look messy and cluttered &#8211; using this code, you can tell it to only display 5 page numbers per page.)<code><span style="color: #000000;"> </span></code></p>
<p><code><span style="color: #000000;"><span style="color: #0000bb;">&lt;?php<br />
</span><span style="color: #ff8000;">/* SNIPE.NET PAGE NUMBERING SNIPPET<br />
Description: This code will allow you to provide item listings<br />
as x per page, and will generate the Pages: 1 2 3, etc links<br />
if needed. You will need to modify the queries as per your<br />
own actual needs, and the database connection/selection code is<br />
not included here, so it's assuming that code is already somewhere else<br />
in your page. (Thats why this code snippet page will give you an error<br />
if it executes - no database info.)</span></span></code></p>
<p>Don&#8217;t get freaked out by how long it is &#8211; 70% of it is comments to<br />
help you understand what it is that we&#8217;re doing. <img src='http://www.snipe.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  */</p>
<p>/* BEGIN CODE SECTION */<br />
/* &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-*/</p>
<p>/* per page limit &#8211; this can be included in a seperate file, as long as you<br />
are sure to include that fle on the page you want the numbering on &#8211; otherwise<br />
its fine to just code it here &#8211; for this example, we&#8217;re using 16 items per page */<br />
<span style="color: #0000bb;">$user_view_limit </span><span style="color: #007700;">= </span><span style="color: #dd0000;">&#8220;16&#8243;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">/* set this variable to whatever the max number of page numbers you wish to be<br />
displayed at any given time */<br />
</span><span style="color: #0000bb;">$max_pages_to_show </span><span style="color: #007700;">= </span><span style="color: #0000bb;">5</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">/* if there is no page # passed, assign $page the value of 1 */<br />
</span><span style="color: #007700;">if ((empty(</span><span style="color: #0000bb;">$page</span><span style="color: #007700;">)) || (</span><span style="color: #0000bb;">$page </span><span style="color: #007700;">&lt;= </span><span style="color: #0000bb;">0</span><span style="color: #007700;">)){<br />
</span><span style="color: #0000bb;">$page </span><span style="color: #007700;">= </span><span style="color: #0000bb;">1</span><span style="color: #007700;">;<br />
}</span></p>
<p><span style="color: #ff8000;">/* this code just figures out the limit for the sql statement that actually<br />
gets that page&#8217;s item data */<br />
</span><span style="color: #0000bb;">$limitvalue </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$page</span><span style="color: #007700;">*</span><span style="color: #0000bb;">$user_view_limit</span><span style="color: #007700;">-(</span><span style="color: #0000bb;">$user_view_limit</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">/* the query to get actual results &#8211; your query would go here, but be sure to<br />
include the LIMIT $limitvalue, $user_view_limit part at the end.<br />
Our example is pulling articles from the &#8220;articles&#8221; table that have the category ID of 2 */<br />
</span><span style="color: #0000bb;">$sql </span><span style="color: #007700;">= </span><span style="color: #dd0000;">&#8220;select Title from articles where CatID=2 LIMIT $limitvalue, $user_view_limit&#8221;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">/* the query to get the total number without the limit */<br />
</span><span style="color: #0000bb;">$sqlcount </span><span style="color: #007700;">= </span><span style="color: #dd0000;">&#8220;select count(*) from articles where CatID=2 &#8220;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">/* this is used by the function in case you need to pass other stuff in your<br />
query string. If you&#8217;re not passing anything else, this should be set to just &#8220;?&#8221;<br />
as is shown in this example -<br />
To pass more variables through the query string, you would just change it to<br />
something like: $print_query =&#8221;?cat_id=$cat_id&amp;&#8221;; */<br />
</span><span style="color: #0000bb;">$print_query </span><span style="color: #007700;">=</span><span style="color: #dd0000;">&#8220;?&#8221;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">/* get the total number data and find out what the grand total is */<br />
</span><span style="color: #0000bb;">$sql_countresult </span><span style="color: #007700;">= </span><span style="color: #0000bb;">mysql_query</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$sqlcount</span><span style="color: #007700;">);<br />
list(</span><span style="color: #0000bb;">$totalrows</span><span style="color: #007700;">) = </span><span style="color: #0000bb;">mysql_fetch_row</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$sql_countresult</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">/* get the actual item data and print it out on the page */<br />
</span><span style="color: #007700;">if (</span><span style="color: #0000bb;">$get_items </span><span style="color: #007700;">= </span><span style="color: #0000bb;">mysql_query</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$sql</span><span style="color: #007700;">)) {<br />
</span><span style="color: #0000bb;">$num_items </span><span style="color: #007700;">= </span><span style="color: #0000bb;">mysql_num_rows</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$get_items</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">/* see if we actually have any matches in the DB */<br />
</span><span style="color: #007700;">if (</span><span style="color: #0000bb;">$num_items </span><span style="color: #007700;">&gt; </span><span style="color: #0000bb;">0</span><span style="color: #007700;">) {</span></p>
<p><span style="color: #ff8000;">/* if theres more than one page needed, print out the page #s<br />
In this example, products.php is the page that the link will be printed out with.<br />
To use a different page, simply change this value in your function call */<br />
</span><span style="color: #007700;">if (</span><span style="color: #0000bb;">$user_view_limit </span><span style="color: #007700;">&lt; </span><span style="color: #0000bb;">$totalrows</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">make_user_page_nums</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$totalrows</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$print_query</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$_SERVER</span><span style="color: #007700;">[</span><span style="color: #dd0000;">'PHP_SELF'</span><span style="color: #007700;">], </span><span style="color: #0000bb;">$user_view_limit</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$page</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$max_pages_to_show</span><span style="color: #007700;">);<br />
}</span></p>
<p><span style="color: #ff8000;">/* print out the actual item details &#8211; you would cange this code to<br />
make it print out the fields and data the way you want it to appear<br />
on the page */<br />
</span><span style="color: #007700;">while (list(</span><span style="color: #0000bb;">$foo</span><span style="color: #007700;">) = </span><span style="color: #0000bb;">mysql_fetch_row</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$get_items</span><span style="color: #007700;">) ) {<br />
echo </span><span style="color: #dd0000;">&#8221;<br />
&#8220;</span><span style="color: #007700;">;<br />
echo </span><span style="color: #0000bb;">$foo</span><span style="color: #007700;">;</span></p>
<p>}</p>
<p><span style="color: #ff8000;">/* if there are no matches, print our an error */<br />
</span><span style="color: #007700;">} else {<br />
echo </span><span style="color: #dd0000;">&#8220;No items listed&#8221;</span><span style="color: #007700;">;<br />
}</span></p>
<p><span style="color: #ff8000;">/* if the query failed, lets see if mysql returns an error */<br />
</span><span style="color: #007700;">} else {<br />
echo </span><span style="color: #dd0000;">&#8220;An error has occurred:<br />
&#8220;</span><span style="color: #007700;">;<br />
echo </span><span style="color: #0000bb;">mysql_error</span><span style="color: #007700;">();<br />
}</span></p>
<p><span style="color: #ff8000;">/* THE ACTUAL make_user_page_nums FUNCTION */<br />
/* &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-*/</span></p>
<p><span style="color: #007700;">function </span><span style="color: #0000bb;">make_user_page_nums</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$total_results</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$print_query</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$page_name</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$results_per_page</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$page</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$max_pages_to_show</span><span style="color: #007700;">) {</span></p>
<p>echo <span style="color: #dd0000;">&#8220;Pages: &#8220;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">/* PREV LINK: print a Prev link, if the page number is not 1 */<br />
</span><span style="color: #007700;">if(</span><span style="color: #0000bb;">$page </span><span style="color: #007700;">!= </span><span style="color: #0000bb;">1</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$pageprev </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$page </span><span style="color: #007700;">- </span><span style="color: #0000bb;">1</span><span style="color: #007700;">;<br />
echo </span><span style="color: #dd0000;">&#8220;.$page_name.$print_query.&#8221;</span><span style="color: #0000bb;">page</span><span style="color: #007700;">=</span><span style="color: #dd0000;">&#8220;.$pageprev.&#8221;"&gt;&lt;Prev &#8220;</span><span style="color: #007700;">;<br />
}</span></p>
<p><span style="color: #ff8000;">/* get the total number of pages that are needed */</span></p>
<p><span style="color: #0000bb;">$showpages </span><span style="color: #007700;">= </span><span style="color: #0000bb;">round</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$max_pages_to_show</span><span style="color: #007700;">/</span><span style="color: #0000bb;">2</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$numofpages </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$total_results</span><span style="color: #007700;">/</span><span style="color: #0000bb;">$results_per_page</span><span style="color: #007700;">;</span></p>
<p>if (<span style="color: #0000bb;">$numofpages </span><span style="color: #007700;">&gt; </span><span style="color: #0000bb;">$showpages </span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$startpage </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$page </span><span style="color: #007700;">- </span><span style="color: #0000bb;">$showpages </span><span style="color: #007700;">;<br />
} else {<br />
</span><span style="color: #0000bb;">$startpage </span><span style="color: #007700;">= </span><span style="color: #0000bb;">0</span><span style="color: #007700;">;<br />
}</span></p>
<p>if (<span style="color: #0000bb;">$startpage </span><span style="color: #007700;">&lt; </span><span style="color: #0000bb;">0</span><span style="color: #007700;">){<br />
</span><span style="color: #0000bb;">$startpage </span><span style="color: #007700;">= </span><span style="color: #0000bb;">0</span><span style="color: #007700;">;<br />
}</span></p>
<p>if (<span style="color: #0000bb;">$numofpages </span><span style="color: #007700;">&gt; </span><span style="color: #0000bb;">$showpages </span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">$endpage </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$page </span><span style="color: #007700;">+ </span><span style="color: #0000bb;">$showpages</span><span style="color: #007700;">;<br />
} else {<br />
</span><span style="color: #0000bb;">$endpage </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$showpages</span><span style="color: #007700;">;<br />
}</span></p>
<p>if (<span style="color: #0000bb;">$endpage </span><span style="color: #007700;">&gt; </span><span style="color: #0000bb;">$numofpages</span><span style="color: #007700;">){<br />
</span><span style="color: #0000bb;">$endpage </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$numofpages</span><span style="color: #007700;">;<br />
}</span></p>
<p><span style="color: #ff8000;">/* loop through the page numbers and print them out */<br />
</span><span style="color: #007700;">for(</span><span style="color: #0000bb;">$i </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$startpage</span><span style="color: #007700;">; </span><span style="color: #0000bb;">$i </span><span style="color: #007700;">&lt; </span><span style="color: #0000bb;">$endpage</span><span style="color: #007700;">; </span><span style="color: #0000bb;">$i</span><span style="color: #007700;">++) {</span></p>
<p><span style="color: #ff8000;">/* if the page number in the loop is not the same as the page were on, make it a link */<br />
</span><span style="color: #0000bb;">$real_page </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$i </span><span style="color: #007700;">+ </span><span style="color: #0000bb;">1</span><span style="color: #007700;">;<br />
if (</span><span style="color: #0000bb;">$real_page</span><span style="color: #007700;">!=</span><span style="color: #0000bb;">$page</span><span style="color: #007700;">){<br />
echo </span><span style="color: #dd0000;">&#8221; .$page_name.$print_query.&#8221;</span><span style="color: #0000bb;">page</span><span style="color: #007700;">=</span><span style="color: #dd0000;">&#8220;.$real_page.&#8221;"&gt;&#8221;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">$real_page</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8221; &#8220;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #ff8000;">/* otherwise, if the loop page number is the same as the page were on, do not make it a link, but rather just print it out */<br />
</span><span style="color: #007700;">} else {<br />
echo </span><span style="color: #dd0000;">&#8220;&#8221;</span><span style="color: #007700;">.</span><span style="color: #0000bb;">$real_page</span><span style="color: #007700;">.</span><span style="color: #dd0000;">&#8220;&#8221;</span><span style="color: #007700;">;<br />
}<br />
}</span></p>
<p><span style="color: #ff8000;">/* NEXT LINK -If the totalrows &#8211; $results_per_page * $page is &gt; 0 (meaning there is a remainder), print the Next button. */<br />
</span><span style="color: #007700;">if((</span><span style="color: #0000bb;">$total_results</span><span style="color: #007700;">-(</span><span style="color: #0000bb;">$results_per_page</span><span style="color: #007700;">*</span><span style="color: #0000bb;">$page</span><span style="color: #007700;">)) &gt; </span><span style="color: #0000bb;">0</span><span style="color: #007700;">){<br />
</span><span style="color: #0000bb;">$pagenext </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$page </span><span style="color: #007700;">+ </span><span style="color: #0000bb;">1</span><span style="color: #007700;">;<br />
echo </span><span style="color: #dd0000;">&#8221; .$page_name.$print_query.&#8221;</span><span style="color: #0000bb;">page</span><span style="color: #007700;">=</span><span style="color: #dd0000;">&#8220;.$pagenext.&#8221;"&gt;Next &gt; &#8220;</span><span style="color: #007700;">;<br />
}</span></p>
<p>}</p>
<p><span style="color: #ff8000;">/* END OF PAGE NUMBERING SNIPPET CODE */<br />
/* &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-*/</span></p>
<p><span style="color: #0000bb;">?&gt;</span></p>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2002/06/page-numbering-with-x-results-per-page/' rel='bookmark' title='Permanent Link: Page Numbering (with x results per page)'>Page Numbering (with x results per page)</a> <small>Although there are several examples of this type of code...</small></li>
<li><a href='http://www.snipe.net/2002/06/phpmysql-breadcrumb-trail/' rel='bookmark' title='Permanent Link: PHP/mySQL Breadcrumb Trail'>PHP/mySQL Breadcrumb Trail</a> <small>This lets you automatically create a breadcrumb trail navigation through...</small></li>
<li><a href='http://www.snipe.net/2010/04/google-analytics-on-facebook-fan-pages/' rel='bookmark' title='Permanent Link: Using Google Analytics on Facebook Fan Pages'>Using Google Analytics on Facebook Fan Pages</a> <small>Can you use Google Analytics on Facebook fan pages and...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2002/06/google-style-page-numbering-with-x-per-page-and-y-page-numbers-displayed/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Page Numbering (with x results per page)</title>
		<link>http://www.snipe.net/2002/06/page-numbering-with-x-results-per-page/</link>
		<comments>http://www.snipe.net/2002/06/page-numbering-with-x-results-per-page/#comments</comments>
		<pubDate>Thu, 27 Jun 2002 15:00:58 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=130</guid>
		<description><![CDATA[Although there are several examples of this type of code to be found online, I had never found one that easily did what I needed and was flexible enough that we only had to change a few things to use it again &#8211; so I wrote my own. It links each page number (except for [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Fpage-numbering-with-x-results-per-page%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Fpage-numbering-with-x-results-per-page%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<p>Although there are several examples of this type of code to be found online, I had never found one that easily did what I needed and was flexible enough that we only had to change a few things to use it again &#8211; so I wrote my own.</p>
<p>It links each page number (except for the current page number), prints Prev and Next links (if they need to be there), and also makes the current page number bold and not linked, like this:</p>
<p><b>Pages: </b>&lt; Prev 1 2 3 4 5 Next &gt;</p>
<p>As you can see, the code is heavily commented to help you understand exactly what it is we&#8217;re doing &#8211; in the event that you actually give a damn. Further down the page, we also have the code for a google-like page number display, showing y page numbers per page. So without any further ado &#8211; check out the code.</p>
<p><b>Description:</b> This code will allow you to provide item listings as x per page, and will generate the Pages: 1 2 3, etc links if needed. You will need to modify the queries as per your<br />
own actual needs, and the database connection/selection code is not included here, so it&#8217;s assuming that code is already somewhere else in your page. (That&#8217;s why this code snippet page will give you an error if it executes &#8211; no database info.)</p>
</p>
<pre lang="php" class="1">Page numbering variables
<?php
/* BEGIN CODE SECTION */
/* â€”â€”â€”â€”â€”â€”â€”â€”â€”â€”â€”â€”â€”-*/

// per page limit - this can be included in a separate
// file, as long as you are sure to include that file on
// the page you want the numbering on - otherwise
// its fine to just code it here - for this example,
// we're using 16 items per page
$user_view_limit = 16;

// if there is no page # passed, assign $page
// the value of 1 

if ((empty($page)) || (intval($page) <= 0)){
	$page = 1;
}

// this code just figures out the limit for the sql
//statement that actually gets that page's item data
$limitvalue = $page*$user_view_limit-($user_view_limit);

// the query to get actual results - your query would
// go here, but be sure to include the LIMIT $limitvalue,
// $user_view_limit part at the end.
// Our example is pulling articles from the "articles"
// table that have the category ID of 2

$sql = "select Title from articles where CatID=2 ";
$sql .= "LIMIT $limitvalue, $user_view_limit";

// the query to get the total number without the limit
$sqlcount = "select count(*) from articles where CatID=2 ";

// this is used by the function in case you need to
// pass other stuff in your query string. If you're not
// passing anything else, this should be set to just "?"
// as is shown in this example -
// To pass more variables through the query string, you
// would just change it to something
// like: $print_query ="?cat_id=$cat_id&#038;";
$print_query ="?";

// get the total number data and find out what the
// grand total is
$sql_countresult = mysql_query($sqlcount);
list($totalrows) = mysql_fetch_row($sql_countresult);

// get the actual item data and print it out on the page
if ($get_items = mysql_query($sql)) {
	$num_items = mysql_num_rows($get_items);

	// see if we actually have any matches in the DB
	if ($num_items > 0) {

		// if theres more than one page needed, print out
		// the page #s. In this example, products.php is the
		// page that the link will be printed out with.
		// To use a different page, simply change
		// this value in your function call 

		if ($user_view_limit < $totalrows) {
			make_user_page_nums($totalrows, $print_query, $_SERVER['PHP_SELF']);
		}

		// print out the actual item details - you would
		// change this code to make it print out the fields
		// and data the way you want it to appear
		// on the page 

		while (list($foo) = mysql_fetch_row($get_items) ) {
			echo $foo;
		}

	// if there are no matches, print our an error
	} else {
		echo "No items listed";
	}

// if the query failed, lets see if mysql returns an error
} else {
	echo "An error has occurred: ";
	echo mysql_error();
}
</pre>
<p>This part below is the actual function that you call<br />
from the page you want the page numbers to display on.
</p>
<pre lang="php" class="85">
function make_user_page_nums($totalrows, $print_query, $page_name) {
	global $user_view_limit;
	global $page;
	global $limitvalue;

	echo "Pages: ";

	// PREV LINK: print a Prev link, if the page number is not 1
	if($page != 1) {
		$pageprev = $page - 1;
		echo ".$page_name.$print_query;
		echo "page=".$pageprev."">&lt; Prev ";
	}

	// get the total number of pages that are needed
	$numofpages = $totalrows/$user_view_limit;

	// loop through the page numbers and print them out
	for($i= 0; $i < $numofpages; $i++) {
		// if the page number in the loop is not
		// the same as the page we're on, make it a link 

		$real_page = $i + 1;

		if ($real_page!=$page){
			echo " .$page_name.$print_query;
			echo "page=".$real_page."">".$real_page." ";

			// otherwise, if the loop page number is the
			// same as the page we're on, do not make it
			// a link, but rather just print it out
		} else {
			echo "".$real_page."";
		}
	} // end for loop

	// NEXT LINK - If the
	// (totalrows - $user_view_limit) * $page is
	// less 0 (meaning there is a remainder), print
	// the Next button. 

	if(($totalrows-($user_view_limit*$page)) > 0){
		$pagenext = $page + 1;
		echo " .$page_name.$print_query."page=".$pagenext."">Next &gt; ";
	}

} // end function
?></pre>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2002/06/google-style-page-numbering-with-x-per-page-and-y-page-numbers-displayed/' rel='bookmark' title='Permanent Link: Google Style Page Numbering (with x per page and y page numbers displayed)'>Google Style Page Numbering (with x per page and y page numbers displayed)</a> <small>With just a few modifications, we can create a piece...</small></li>
<li><a href='http://www.snipe.net/2009/06/fb-fanpages-fbml-box/' rel='bookmark' title='Permanent Link: Static FBML: Not Every Facebook Fan Page Needs An Application'>Static FBML: Not Every Facebook Fan Page Needs An Application</a> <small>You don&#8217;t always need a custom application for your Facebook...</small></li>
<li><a href='http://www.snipe.net/2010/05/facebook-fan-pages-10k/' rel='bookmark' title='Permanent Link: Want to Set a Default Landing Tab on Your Facebook Fan Page? It&#8217;ll Cost You'>Want to Set a Default Landing Tab on Your Facebook Fan Page? It&#8217;ll Cost You</a> <small>You&#8217;re gonna love this. And by love I mean be...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2002/06/page-numbering-with-x-results-per-page/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Alternating Row Colors in PHP/mySQL</title>
		<link>http://www.snipe.net/2002/06/alternating-row-colors-in-phpmysql/</link>
		<comments>http://www.snipe.net/2002/06/alternating-row-colors-in-phpmysql/#comments</comments>
		<pubDate>Wed, 19 Jun 2002 16:05:57 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=29</guid>
		<description><![CDATA[Using alternating row colors in a PHP database application is a nice way to give the user some visual differentiation between multiple rows of results &#8211; and the best part is that it&#8217;s so damn easy.  I&#8217;m going to assume that you&#8217;re using CSS for formatting, but if you are still using HTML to set [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Falternating-row-colors-in-phpmysql%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Falternating-row-colors-in-phpmysql%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<p>Using alternating row colors in a PHP database application is a nice way to give the user some visual differentiation between multiple rows of results &#8211; and the best part is that it&#8217;s so damn easy.  I&#8217;m going to assume that you&#8217;re using CSS for formatting, but if you are still using HTML to set attributed like background colors in your database results out table (gasp!), you can still make this code work just as easily.  In this example, we are using the CSS elements <strong>resultline</strong> and <strong>resultlinealt</strong>, but you can name them whatever you like.<span id="more-29"></span></p>
<pre class="brush: php">
/* OUTSIDE of the SQL loop, set a zero value for the rowcolor
* variable, which is basically just our row counter.
*/
$rowcolor = 0;

/* Set values for your two different CSS styles here */
$report_class = ($rowcolor % 2) ? &#039;resultline&#039; : &#039;resultlinealt&#039;;

/* Loop through the database results and print out
* the table rows - this example query assums we have
* executed a query asking for the name and address within a
* given table */
while (list($name, $address) = mysql_fetch_row($resultt)){
echo &#039;&lt;tr&gt;&lt;td class=&quot;&#039;.$report_class.&#039;&quot;&gt;&#039;.$name.&#039;&lt;/td&gt;&lt;/tr&gt;&#039;;
$rowcolor++;
}
</pre>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2008/12/ip-geolocation-radius-search-in-php/' rel='bookmark' title='Permanent Link: Using IP Geolocation and Radius Searching with PHP/MySQL'>Using IP Geolocation and Radius Searching with PHP/MySQL</a> <small>Delivering content relative to the physical location of your users...</small></li>
<li><a href='http://www.snipe.net/2002/06/page-numbering-with-x-results-per-page/' rel='bookmark' title='Permanent Link: Page Numbering (with x results per page)'>Page Numbering (with x results per page)</a> <small>Although there are several examples of this type of code...</small></li>
<li><a href='http://www.snipe.net/2006/06/creating-a-multi-level-listbox-in-phpmysql/' rel='bookmark' title='Permanent Link: Creating a Multi-Level Listbox in PHP/mySQL'>Creating a Multi-Level Listbox in PHP/mySQL</a> <small>This lets you create a nested multi-level category menu through...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2002/06/alternating-row-colors-in-phpmysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP/mySQL Breadcrumb Trail</title>
		<link>http://www.snipe.net/2002/06/phpmysql-breadcrumb-trail/</link>
		<comments>http://www.snipe.net/2002/06/phpmysql-breadcrumb-trail/#comments</comments>
		<pubDate>Wed, 19 Jun 2002 15:48:50 +0000</pubDate>
		<dc:creator>snipe</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[PHP/mySQL]]></category>
		<category><![CDATA[breadcrumbs]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://www.snipe.net/?p=22</guid>
		<description><![CDATA[This lets you automatically create a breadcrumb trail navigation through PHP and mySQL, that would look something like: Home &#62;&#62; Parrots &#62;&#62; Red Parrots This type of dynamic breadcrumb trail is only possible when you are storing the menu items (or categories) in a table, that contains at least a name, a category id number [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: left; margin-right: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Fphpmysql-breadcrumb-trail%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.snipe.net%2F2002%2F06%2Fphpmysql-breadcrumb-trail%2F&amp;source=snipeyhead&amp;style=normal&amp;service=bit.ly&amp;service_api=R_92bd97f4f8b9fa8a40675b36ea291223" height="61" width="50" /><br />
			</a>
		</div>
<div></div>
<div>This lets you automatically create a breadcrumb trail navigation through PHP and mySQL, that would look something like: <strong></strong></div>
<div>
</div>
<div>
</div>
<div><strong>Home &gt;&gt; Parrots &gt;&gt; Red Parrots</strong></div>
<div>
</div>
<div><strong></strong>This type of dynamic breadcrumb trail is only possible when you are storing the menu items (or categories) in a table, that contains at least a name, a category id number and a parent category id number.<span id="more-22"></span></div>
<p><code><span style="color: #000000;"> <span style="color: #0000bb;">&lt;?php<br />
</span><span style="color: #ff8000;">/* ---------------------------------------------- */<br />
/* ------------ BEGIN PHP SNIPPET ----------------*/<br />
/* ---------------------------------------------- */<br />
// $this_cat_id: the current category id number<br />
// $flarn: just a counter, call it as 0 in your<br />
// function call and forget about it<br />
// $keep_cat_id: the cat id number again - so that<br />
// it can decide whether to make a<br />
// category a link at the top while you're in the<br />
// "product" page</span></span></code></p>
<p><span style="color: #007700;">function </span><span style="color: #0000bb;">get_crumbs</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$this_cat_id</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$keep_cat_id</span><span style="color: #007700;">) {</span></p>
<p><span style="color: #0000bb;">$link_to_page</span><span style="color: #007700;">=</span><span style="color: #0000bb;">$_SERVER</span><span style="color: #007700;">[</span><span style="color: #dd0000;">'PHP_SELF'</span><span style="color: #007700;">];<br />
if (!isset(</span><span style="color: #0000bb;">$this_cat_id</span><span style="color: #007700;">)) {<br />
</span><span style="color: #ff8000;">// if we are already &#8220;home&#8221;, dont make home a link<br />
</span><span style="color: #0000bb;">$this_cat_id </span><span style="color: #007700;">=</span><span style="color: #dd0000;">&#8220;0&#8243;</span><span style="color: #007700;">;<br />
echo </span><span style="color: #dd0000;">&#8220;Home &lt;&lt; &#8220;</span><span style="color: #007700;">;<br />
}<br />
</span><span style="color: #ff8000;">// get the info and parent id for whatever category<br />
// we&#8217;re currently in</span></p>
<p><span style="color: #0000bb;">$sql </span><span style="color: #007700;">= </span><span style="color: #dd0000;">&#8220;SELECT id, parent_id, name from categories &#8220;</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$sql </span><span style="color: #007700;">.=</span><span style="color: #dd0000;">&#8220;where id = $this_cat_id&#8221;</span><span style="color: #007700;">;</span></p>
<p><span style="color: #0000bb;">$show_crumb_trail </span><span style="color: #007700;">= </span><span style="color: #0000bb;">mysql_query</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$sql</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$num_crumbs </span><span style="color: #007700;">= </span><span style="color: #0000bb;">mysql_num_rows</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$show_crumb_trail</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">// if we actually have some results&#8230;.<br />
</span><span style="color: #007700;">if (</span><span style="color: #0000bb;">$num_crumbs </span><span style="color: #007700;">&gt; </span><span style="color: #0000bb;">0</span><span style="color: #007700;">) {<br />
list(</span><span style="color: #0000bb;">$cat_id</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$cat_parent</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$cat_name</span><span style="color: #007700;">) = </span><span style="color: #0000bb;">mysql_fetch_row</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$show_crumb_trail</span><span style="color: #007700;">);<br />
</span><span style="color: #0000bb;">$cat_id_array</span><span style="color: #007700;">[</span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">] = </span><span style="color: #0000bb;">$cat_id</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$cat_parent_id_array</span><span style="color: #007700;">[</span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">] = </span><span style="color: #0000bb;">$cat_parent</span><span style="color: #007700;">;<br />
</span><span style="color: #0000bb;">$cat_name_array</span><span style="color: #007700;">[</span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">] = </span><span style="color: #0000bb;">$cat_name</span><span style="color: #007700;">;<br />
if (</span><span style="color: #0000bb;">$cat_id_array</span><span style="color: #007700;">[</span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">] &gt; </span><span style="color: #0000bb;">0</span><span style="color: #007700;">) {<br />
</span><span style="color: #0000bb;">mysql_free_result</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$show_crumb_trail</span><span style="color: #007700;">);<br />
</span><span style="color: #ff8000;">// increment $next by one<br />
</span><span style="color: #0000bb;">$next </span><span style="color: #007700;">= </span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">+</span><span style="color: #0000bb;">1</span><span style="color: #007700;">;<br />
if (</span><span style="color: #0000bb;">$flarn </span><span style="color: #007700;">== </span><span style="color: #0000bb;">0 </span><span style="color: #007700;">) {<br />
echo </span><span style="color: #dd0000;">&#8220;Home &lt;&lt; &#8220;</span><span style="color: #007700;">;<br />
}<br />
</span><span style="color: #ff8000;">// now lets call the function again to loop through<br />
// the other categories<br />
// until we&#8217;re left with none<br />
</span><span style="color: #0000bb;">get_crumbs</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$cat_parent_id_array</span><span style="color: #007700;">[</span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">], </span><span style="color: #0000bb;">$next</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$keep_cat_id</span><span style="color: #007700;">);</span></p>
<p><span style="color: #ff8000;">// Since $keep_cat_id is the id number of original<br />
// category we&#8217;re in,<br />
// now we check to see whether or not we have to<br />
// make the real category<br />
// name a link or not<br />
// (If we&#8217;re looking at the main category display,<br />
// we wouldn&#8217;t have to,<br />
// since we&#8217;re already *in* the category.Â Â This is<br />
// more useful for when you have a product<br />
// display page, that way the link back to the<br />
// category that item orÂ Â product lives in<br />
// will be created<br />
</span><span style="color: #007700;">if (</span><span style="color: #0000bb;">$keep_cat_id</span><span style="color: #007700;">==</span><span style="color: #0000bb;">$cat_id_array</span><span style="color: #007700;">[</span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">]) {<br />
echo </span><span style="color: #0000bb;">$cat_name_array</span><span style="color: #007700;">[</span><span style="color: #0000bb;">$flarn</span><span style="color: #007700;">];<br />
} else {<br />
echo </span><span style="color: #dd0000;">&#8220;$cat_name_array[$flarn] &lt;&lt; &#8220;</span><span style="color: #007700;">;<br />
}<br />
}<br />
}<br />
}<br />
</span><span style="color: #0000bb;">?&gt;</span></p>
<p>You would call the function using something like this:</p>
<p><code><span style="color: #000000;"> &lt;php get_crumbs($_REQUEST['cat_id'], "0", $_REQUEST['cat_id']; ?&gt;</span> </code></p>


<p>Possibly related posts:<ol><li><a href='http://www.snipe.net/2006/06/creating-a-multi-level-listbox-in-phpmysql/' rel='bookmark' title='Permanent Link: Creating a Multi-Level Listbox in PHP/mySQL'>Creating a Multi-Level Listbox in PHP/mySQL</a> <small>This lets you create a nested multi-level category menu through...</small></li>
<li><a href='http://www.snipe.net/2002/06/page-numbering-with-x-results-per-page/' rel='bookmark' title='Permanent Link: Page Numbering (with x results per page)'>Page Numbering (with x results per page)</a> <small>Although there are several examples of this type of code...</small></li>
<li><a href='http://www.snipe.net/2002/06/google-style-page-numbering-with-x-per-page-and-y-page-numbers-displayed/' rel='bookmark' title='Permanent Link: Google Style Page Numbering (with x per page and y page numbers displayed)'>Google Style Page Numbering (with x per page and y page numbers displayed)</a> <small>With just a few modifications, we can create a piece...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.snipe.net/2002/06/phpmysql-breadcrumb-trail/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
