Base href, the simple solution

Posted: October 13th, 2014 | Author: | Filed under: HTML, Internet, PHP | No Comments »

I’ve been grappling for a while with a problem. The site I’d created, due to using mod_rewrite to create URLs that didn’t actually exist, was creating a virtual folder structure that meant that I was having to create specific sidebars and navigation elements that included the right level of linking.

This being a PHP site, I’d tried to resolve this by using variables such as $_SERVER[‘PHP_SELF’] to try and automatically resolve the server address to provide a relative file path, but this had mixed results.

Turns out that the answer was the not frequently mentioned base html tag – this is a tag that I was sort of aware of, but had forgotten. Indeed, an otherwise excellent HTML book I read the other day didn’t even mention it…

Simply adding

 <base href = "" /> 

to the site made included headers, sidebars etc instantly portable, no matter the folder depth.

Of course, this being a PHP site, I set the base URL in my site’s config file i.e.

$baseurl = "";

then called that in my site header:

 <base href = "<?php echo $baseurl ?>" /> 

so I only have to change the config file for different servers/environments.

Converting MYSQL DATEs for PHP

Posted: July 30th, 2012 | Author: | Filed under: Internet, MYSQL, PHP, Programming | No Comments »

A site I am working on stores the date of new entries to the database by using MYSQL’s CURDATE() function. So if we’re adding a new entry with the make, model and date to the database, the SELECT query looks like this:

"INSERT INTO table_name (make, model, date) VALUES ($make, $model, CURDATE())"

This works fine, but when I then query the database, like so:

"SELECT make, model, date FROM table_name WHERE ..."

The date returned is in MYSQL’s date format, which is YYYY-MM-DD.
I was looking around for a quick and easy way to convert this in PHP to the UK DD-MM-YYYY format, and kept coming up with longwinded ideas for converting the MYSQL date to a UNIX timestamp, and then using all kinds of guff to format this as required.
It turns out the answer’s much simpler than that, if you use MYSQL’s DATE_FORMAT function. By passing in your date column and the format in which you want it presented you can create a new variable to query. So the previous query becomes:

"SELECT make, model DATE_FORMAT(date, '%d/%m/%Y') as formatted_date FROM table_name WHERE ..."

The %d/%m/%Y part is where you define how the date should be formatted. Dan Winchester has an excellent and comprehensive list of options on his website.

Now, instead of your PHP looking like:

$make = $row['make'];
$model = $row['model'];
$date = $row['date'];

it becomes:

$make = $row['make'];
$model = $row['model'];
$date = $row['formatted_date'];

thus returning your date information nicely pre-formatted by MYSQL.