Categories

What others think…

More from Peter

Handling empty mysql return via php

This is a simple script that will allow you to display a simple message when your mysql query returns no results. i.e. Sorry, but your search returned no results.
Examples can be found at The Expat Directory in the used car section. just look for a category that’s empty. In the The Expat Directory example, I also added a google search button so that customers are provided with a simple interface that encourages them to stay within the parent website.

Anyway…
It is funny how you can sometimes spend hours creating the perfect script and query results to achieve the desired web content. What isn’t funny is when you reach the stage where your site is almost complete and empty your mysql database of the test content only to realise that you forgot to allow for your null outputs through php – damn….

Does this look familiar?

Quote:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-2,2′ at line 1

This is just one syntax error that may be thrown up when your code suddenly realises that there’s nothing to display, the query string has returned an empty result.

So, how do we get around this? Actually, it’s very simple.

Look at the script below

PHP Code:

$result = mysql_query(some old query);  //This is your standard MYSQL query
if (mysql_num_rows($result) > 0)

{

while ($row = mysql_fetch_assoc($result))

{

// This is where you would either echo your results, chop to html and output via a table or whatever it is you want to do with your query
}
}

else

{

echo “No results found, why not visit www.peterstarmer.com instead.”;  // This is where you insert a message to let you users know that there is are no results.
}

Much better than a messy syntax error.
This is a very simple solution but easily overlooked. The argument provided is simple, if the results = 1 or more, print them, if there are no results, print a message. Note that it isn’t necessary to redirect your users to this website, but you are more than welcome to if you wish

Mysql timestamp results GROUP BY year, Group BY month etc


The inbuilt MySQL functionality timestamp provides the perfect means of specifying when specific data is submitted to a MySQL table (whether on initial insert, update whatever).

The display width of MySQL timestamp is fixed at 19 characters and is automatically formatted at ‘YYYY-MM-DD HH:MM:SS’

Retrieving and displaying the Mysql Timestamp will, as default, mirror the format as the timestamp is stored in Mysql i.e. ‘YYYY-MM-DD HH:MM:SS’

The timestamp output can be modified to a more user friendly output by using one of the following PHP codes:

First, the example array query:

PHP Code:

$query = mysql_query(“SELECT a, b, c, timestamp FROM yourmysqltable “) or die(mysql_error());
while($result = mysql_fetch_array( $query ))

To Display a MySQl timestamp output of Year, Month, Date:

PHP Code:

<? echo date(‘Y-m-d’, strtotime($result['timestamp'])); ?>

To Display a MySQl timestamp output showing just the Year:

PHP Code:

<? echo date(‘Y’, strtotime($result['timestamp'])); ?>

To Display a MySQl timestamp output showing just the Month:

PHP Code:

<? echo date(‘m’, strtotime($result['timestamp'])); ?>

To Display a MySQl timestamp output showing just the Day:

PHP Code:

<? echo date(‘d’, strtotime($result['timestamp'])); ?>

and so on for hours (h) Minutes (i) and Seconds (s)

PHP has a plethora of inbuilt functionality which can be applied to the timestamp format to achieve any number of desired time outputs, the following reference should assist you in achieving the timestamp format that you need:

Time:

  • a: am or pm depending on the time
  • A: AM or PM depending on the time
  • g: Hour without leading zeroes. Values are 1 through 12.
  • G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.
  • h: Hour with leading zeroes. Values 01 through 12.
  • H: Hour in 24-hour format with leading zeroes. Values 00 through 23.
  • i: Minute with leading zeroes. Values 00 through 59.
  • s: Seconds with leading zeroes. Values 00 through 59.

Day:

  • d: Day of the month with leading zeroes. Values are 01 through 31.
  • j: Day of the month without leading zeroes. Values 1 through 31
  • D: Day of the week abbreviations. Sun through Sat
  • l: Day of the week. Values Sunday through Saturday
  • w: Day of the week without leading zeroes. Values 0 through 6.
  • z: Day of the year without leading zeroes. Values 0 through 365.

Month:

  • m: Month number with leading zeroes. Values 01 through 12
  • n: Month number without leading zeroes. Values 1 through 12
  • M: Abbreviation for the month. Values Jan through Dec
  • F: Normal month representation. Values January through December.
  • t: The number of days in the month. Values 28 through 31.

Year:

  • L: 1 if it’s a leap year and 0 if it isn’t.
  • Y: A four digit year format
  • y: A two digit year format. Values 00 through 99.

Other Formatting:

  • U: The number of seconds since the Unix Epoch (January 1, 1970)
  • O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours

So, all fairly straight forward so far?

Now what if you want to group your Mysql timestamp results by the year and then display them?

First, the example array query:

PHP Code:

$query = mysql_query(“SELECT a, b, c, date_format(timestamp, ‘%Y’) AS bob FROM yourmysqltable GROUP BY bob”) or die(mysql_error());
while($result = mysql_fetch_array( $query ))

Now we can display our mysql results and group them using the timestamp.

To Display a MySQl timestamp results grouped by YEAR:

PHP Code:

<? echo $archive['bob']; ?>

The Same principal can then be applied to group results by the corresponding month etc. In the example above, the result would be to output the year i.e. 2009. by expanding on this basic query, you can easily expand the output results to show all mysql results within the year specified.

I hope this throws a little light onto how to use MySQL timestamp effectively. For more information on MySQl timestamp functionality, consult the manual.

using a div tag to create a scrollable area within your webpage - a scrollbar div

This is a simple snippet of code that will allow you to add a scrollbar area of information within a webpage.

Why would I use this?

If you have a large amount of text, mysql results large data array etc and you want to display all the content but don’t want a huge list of data messing up your page design, simply place the content within the div tags and you instantly get a cleaner, user friendly page. beats using an iframe and can be called using via css et al for great customisation (scrollbar colouring, background colouring et al).

HTML Code:

<div style=”width: 450px; height: 250px; overflow: auto”>

Your content / mysql query goes here

</div>

Setting overflow to auto will allow all the content to be displayed normally until the fixed size specified is exceeded, then the scrollbar becomes visible. Note that you do not have to specify both width and size, shown here purely for example

Passing data from page to page when using pagination using php

There are numerous articles out there about pagination and just as many different approaches to achieving pagination of mysql data using php.

I do not intend to add another pagination script to the plethora of existing php pagination scripts but what I will do is add a simple piece of script that is often omitted from pagination scripts. A simple script yet invaluable for passing data across paginated webpages.  A good pagination script will not need this hack but I have posted the solution in response to a call for help.

Scenario
You already have a mysql database set up and are happy with inserting, updating, deleting data to your mysql database.

You know how to retrieve mysql results with php and display the results using tables and so on.

You have found/written a php pagination script that handles your query and it all works well until….

you use a form to send information to your paginated page, it displays the first page list of results but not the second or third or… so on.

The problem
The problem is caused because you have not sent the Form GET – POST information onto the subsequent paginated pages (I know you scream, but how do I fix this).

A simple way to fix this is to:

  • take the results from your form (whether they are sent with POST or GET)
  • make them a variable
  • generate a cookie
  • make the cookie a variable you can work with
  • provide the ability to update the cookie if you send new post data to the paginated page (from a drop down form for example)

The Script

PHP Code:

if(isset($_GET['Your_Form_Input']))
{
$getforminput=$_GET['Your_Form_Input'];
setcookie(“somecookie”,$getforminput, time()+240);
$output_variable = $_GET['Your_Form_Input'];
}
if(!isset($_GET['Your_Form_Input']))
{
$output_variable = $_COOKIE['somecookie'];
}

So what does all this mean then?

Well….

PHP Code:

if(isset($_GET['Your_Form_Input']))

First we use the if construct to identify if a certain situation exists, in this case we want to identify whether an input has been received from a form.
further info on IF here

isset is used to determine whether a variable has been set (think is it set? – isset). In this case we are checking if the page has recieved a form input.
further info on isset here

Now, if the situation is true then we will make an output inside our curly braces { to start and } to end.

PHP Code:

{
$getforminput=$_GET['Your_Form_Input'];
setcookie(“somecookie”,$getforminput, time()+240);
$output_variable = $_GET['Your_Form_Input'];
}

The above code defines our output to execute once our if statement is true.

Line by Line:

We have now determined that our input has been received from a form and is therefore a NEW input.

PHP Code:

$getforminput=$_GET['Your_Form_Input'];

Here we are simply making our form output into a variable that we can use later (to influence our mysql results for example)

PHP Code:

setcookie(“somecookie”,$getforminput, time()+240);

We now want to transfer our variable into a cookie so that is can be used on subsequant pages (for pagination in this example). In this example I have set the cookie name to somecookie, asigned the value as our variable $getforminput and set the cookie to expire in 4 minutes (240 seconds)
further info on Setting Cookies here

PHP Code:

$output_variable = $_GET['Your_Form_Input'];

Okay, now the part which may cause some confusion. Hopefully this will be clear enough, if not join the forum and post a message – please note that you have to contact us to request membership (to stop spammers )

We now assign another variable which can be used in your mysql query to retrieve specific mysql results). In this instance we are setting our output variable (name it what you want) to reflect the value of our form input.

i.e.

Code:

SELECT * FROM your_table WHERE some_column = ‘$output_variable’

So, the above code dealt with handling the paginated results when the information was received from a form. Now we will look at what to do when we move onto our second, third, etc paginated page and the form data is no longer present.

Second part of the code

PHP Code:

if(!isset($_GET['Your_Form_Input']))
{
$output_variable = $_COOKIE['somecookie'];
}

In the first part of our code we captured the information from our form, made this a variable, assigned it to a cookie and assigned a variable for our mysql query (based on our form input).

In the second part of our code, we again use the if and isset functions to determine whether a post has been made. Note the slight difference in the isset line, isset is now prefixed with a ! – this changes the command from IS SET to IS NOT SET.
In the first part of the script we defined what should happen if a result was received from a form, in the second part of the script we are defining what should happen if a result is NOT received from a form.

In this case we use the cookie we created in part one as our variable value for our Mysql query. This enables us to pass the information from our form across several pages until:

  • the cookie expires (time based)
  • the cookie value is changed by a new form input

Summary
This is a very simple way to allow information to be passed across paginated pages in php. There are alternative options using if and else and elseif. This article has simply provided a simple solution which should allow a wider audience to pass the hurdle that is created by using form inputs on php pagination pages.
If you do find this article useful, I always appreciate a link back to the site – Thanks

Code:

<a href=”http://www.peterstarmer.com/”> Peter Starmer – A myriad of thoughts</a>

.htaccess IP redirect to another domain

If you run a website or blog, it is almost inevitable that at some point, your site will be hacked.

Whilst the simple reaction is to get annoyed and moan about internet hackers and what motivates them, it is simpler to just accept that you’ve been hacked.

Website hackers or Internet Hackers (whatever you prefer to call them), tend to be a very savvy bunch who tend to do their research well.  In most instances, a hacker will review your website or blog methodically and, in most instances, will have a better idea of the security capabilities and limitations of your site than you will.  There are a number of factors which motivate hackers, some do it for the ‘buzz’, others to further their careers (what better way to open a door to McAfee, Norton or Kaspersky?) and there are of course those who are simply malicious and want to bring the internet down.  Whatever the motivation, there is no point it getting frustrated or moaning, just deal with it.  You will never win with hackers, just settle for a draw:)

Anyway, if your reading this article then the chances are that you have been hacked and you are wondering what you can do to stop the hacker returning?  Well, not a lot really :)  the hackers will return, it’s just up to you how you deal with them.  The information below will show you how to modify your .htaccess file to redirect an individual originating from a specific IP address to another website or simply to just block them from viewing your site.  Remember, most hackers will actively IP hop (change IP addresses), so blocking/redirecting via .htaccess is a tool to help prevent further attacks, i is not a golden chalice that will make you secure forever.

Assuming you have the IP address for the hacker (gathered via your post data, web tracker or other data gatherer), you can modify your root folder .htaccess as follows:

To permanently block a single IP address

order allow,deny
deny from 209.222.133.187
allow from all

To permanently block several IP addresses

order allow,deny
deny from 209.222.133.187
deny from 85.12.16.224
allow from all

[insert additional IP addresses as required]

To permanently redirect a single IP address

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^209\.222\.133\.187$
RewriteRule .* http://www.somedomainorother.co.uk [R,L]

To permanently redirect several IP addresses

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^209\.222\.133\.187$ [OR]
RewriteCond %{REMOTE_ADDR} ^85\.12\.16\.224$
RewriteRule .* http://www.somedomainorother.co.uk [R,L]

[Insert additional IP addresses as required, note the addition of [OR] at the end of the first line IP address]

What if I am getting hacked by multiple IPs from the same block (range)?

Okay, you don’t want to have to fill your .htaccess with a huge range of IP addresses for redirection/blocking as this would be painful for you and make your .htaccess file a bit on the large side.  Assuming you are being hacked by a series of IPs from the same block:

209.222.133.181

209.222.133.182

209.222.133.183

209.222.133.184

209.222.133.185

209.222.133.186

rather than add every IP, you can shorten the blocked IP to 209.222.133, this would then block every IP from 209.222.133.0 to 209.222.133.255.  So returning to our blocking example:

To permanently block several IP addresses and an entire IP block

order allow,deny
deny from 209.222.133
deny from 85.12.16.224
allow from all

Whilst this will provide the carte blanche block, you should be wary of overusing this approach as you may inadvertently stop your users viewing your website.

This covers the IP side of life.  If you also discover that all hacking activity originates from a specific website, you can block the domain in the same manner

To permanently block activity received from another web domain

order allow,deny
deny from somehackingsitesomewhere.co.uk
allow from all

In Summary, we looked at how we can deal with IP addresses and specific domains who send unwanted traffic to your website.  The important point to remember is that this is just a tool, it is not a cure for the problem.  You must still trace down how the hacker accessed your site scripts / database and ensure that the door is closed to further unwanted activity.

SEO friendly Image (img) tags

HTML img tags are used to insert an image in a specific point of a webpage.

GIFs, JPEGs, and PNGs are image formats used to display images on websites.  Each image format has its own strengths and weaknesses and you should consider the following article when choosing which format is appropriate for your select image.

Selecting the appropriate image and adding the correct image tag attributes is essential for ensuring that both SEO and  Web Page load speeds are optimal.

The Correct HTML Image Tag Format

<img src=”http://www.peterstarmer.com/images/DSCF2192.JPG” title=”An example image” alt=”Winter Snow” height=”300″ width=”200″ />

Winter Snow
In the example above the height and width would reduced the image from is actual size.  This in itself would reduce page speed optimisation.  Images which are consistently used in the same space, filling the same area should be scaled down to fit the actual image content area

So, what do the tag attributes and declarations mean?

1. src attribute – specifies the URL of the image.  This can be either relative or an absolute URL (there are mixed opinions on which is the best approach, I will not discuss it here as its a post in its own right)
2. width declaration – specifies the width of the image (in pixels [as shown] or percentage.  Pixels is recommended)*
3. A height declaration – specifies the height of the image (in pixels [as shown] or percentage.  Pixels is recommended)*
4. An alt attribute – used to specify the content of the image —this is focal point of image SEO, search engine spiders cant see images (no surprise there) and they focus on the alt tag as the primary data reference (followed by title and then surrounding text, page text and so on).
5. A title attribute – Used to provide an descriptive pop-up message which is displayed to the user when the mouse hovers over the image.

* The image size attributes are of course present within the image data itself and not using the image size declarations will not stop the image from appearing.  The image would still appear but the browser load speed would be reduced as the surrounding content will be re-wrapped to include the image after is loads.  By specifying the image size declarations, the browser knows exactly what dimensions the image will load at and therefore builds the page content layout in a single instance.  Whilst the page load speeds may be very small for a single image, several images soon add up to a slower page load.  Take a look at The Expat Directory Galleries where some pages contain over 600 1MB images

A New Beggining

Well, I finally decided to start capturing all my thoughts and sharing them with anyone that happens to be interested.
Wordpress is a great tool so it made sense to opt for a collaborative cms solution that would suit my needs.
This blog will contain my thoughts, events and various posts on topics and discussions that I feel are interesting and worth sharing. You are welcome to add comments and post your opinions as you see fit. Lets just see how it takes shape.