PHP snippets
PHP, MySQL, Javascript, HTML and CSS code examples.

PHP add leading zeros

Posted: April 6th, 2011 | Author: admin | Filed under: PHP, Uncategorized | No Comments »

Here is a simple way to add leading zeros to a number. For example you have your day of the month 8 and you want to display it as 08.

1
2
3
$day = 8;

echo sprintf("%02d",$day); //displays 08

MySQL remove trailing characters from a field

Posted: February 26th, 2011 | Author: admin | Filed under: MySQL | No Comments »

Sometimes you want to trim trailing characters (other than spaces) from a field, like an URL.  MySQL TRIM function removes only spaces from a string. So for example if we have an url http://www.mysite.com/test/ and you want to remove the trailing / this is how is done, using TRAILING keyword:

1
2
3
SELECT TRIM(TRAILING '/' FROM myfield ) FROM mytable;

#the result will be http://www.mysite.com/test

Also you can use TRIM function to remove starting characters in a string using LEADING keyword instead of TRAILING

1
2
3
4
SELECT TRIM(LEADING 'http://' FROM myfield ) FROM mytable;

#this will remove http:// from beginning of the string,
#the result will be: www.mysite.com/test/

And if you want to remove both leading and trailing characters, you can use BOTH keyword

1
2
3
4
SELECT TRIM(LEADING 'aa' FROM 'aabcdaa');

#this will remove 'aa'  from beginning and end of the string,
#the result will be: bcd

And at last, if you have thousands of records and you want to remove last characters from all records, you can do this very easy using TRIM function

1
UPDATE `mytable` SET myfield=TRIM(TRAILING '/' FROM myfield );

PHP best practices #2 – use a file versioning system

Posted: January 19th, 2011 | Author: admin | Filed under: Best Practices, PHP | No Comments »

It is recommended that you develop your code on one machine, and deploy it on another machine. Never develop the code on the production server!!! You create the code, test it good, and when it all works as it should be, the code will be copied on production server. How is this done? Using a file versioning system like svn or git. I use svn because Im used to it.

The main advantages of using a file versioning system are:

  • you don’t have to copy all the files to production server, svn will update only the modified ones
  • you will have a history of modifications, if something goes wrong with the current version you can easily switch to a previous version that work
  • more people can work on the same code without messing things up

PHP log errors

Posted: January 13th, 2011 | Author: admin | Filed under: PHP | No Comments »

It is recommended that you log PHP errors to a file instead of displaying them to your clients. Good thing you can do this very easy in PHP, but I don’t understand why many developer don’t log the errors and still display warnings and errors to visitors. Here is how you can log errors to a file using ini_set() PHP function:

1
2
3
ini_set( "log_errors" , "1");
ini_set( "error_log" , "error_file.log" );
ini_set( "display_errors" , "0" );

Of course you can set how errors are logged using .htaccess file

1
2
3
php_value log_errors on
php_flag display_errors off
php_value error_log /path/to/error.log

And you should check error log files often to see and fix errors quick.


MySQL convert string to date

Posted: January 11th, 2011 | Author: admin | Filed under: MySQL | No Comments »

There are cases when you have a date formatted in %d.%m.%Y format for example, and you want to compare it with some %Y-%m-%d date. You need to convert %d.%m.%Y string to a %Y-%m-%d format date. Mysql has such a function STR_TO_DATE that accepts two parameters, date and format date is.

For example

$date = ’04.05.2011′;

And you want to convert it using MySQL to 2011-05-04

1
SELECT STR_TO_DATE('04.05.2011','%d.%m.%Y') AS date_formatted

This will return ’2011-05-04′, so all you have to do is specify the string and the date format that string is.


Set MySQL sql_mode in my.ini

Posted: January 11th, 2011 | Author: admin | Filed under: MySQL | No Comments »

You can change MySQL sql_mode from my.ini on a windows server by using the following line:

# Set the SQL mode to strict
sql-mode=”STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION”

There are multiple sql modes, by default sql-mode is ” which means no restriction, no validation checks. But you can change the sql_mode at runtime or in my.ini file. If you want to check the sql mode you can use:

1
SELECT @@sql_mode;

If you want to change the sql mode during runtime, you can use:

1
2
3
SET sql_mode = 'IGNORE_SPACE, ANSI_QUOTES';
SET sql_mode = 'STRICT_ALL_TABLES, ERROR_FOR_DIVISION_BY_ZERO';
SET sql_mode = '';

More about MySQL sql_modes http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html


PHP remove non numeric characters

Posted: January 7th, 2011 | Author: admin | Filed under: PHP | No Comments »

There are cases when you want to filter all the characters except the numeric ones (0-9) from a string.

Here are several ways to remove non numeric characters from a string:

  • 1. using preg_replace function
1
2
$string = 'abc345 %^FGA33';
$filter_string = preg_replace( '/\D/', '', $string ); //will return 34533
  • 2. using ereg_replace function
1
2
$string = 'abc345 %^FGA33';
$filter_string = ereg_replace( "[^0-9]", "", $string ); //will return 34533
  • 3. using ereg_replace function (another way)
1
2
$string = 'abc345 %^FGA33';
$filter_string = eregi_replace('[^[:digit:]]', '', $string ); //will return 34533

jQuery cancel default action of an event

Posted: December 16th, 2010 | Author: admin | Filed under: Javascript | No Comments »

There are cases when you want to prevent the default action of an event. For example when a link is clicked, you want to do some javascript before following that link. Or you want to cancel the following of the link.

This is done easily with jQuery using preventDefault() method.

1
2
3
4
$("a").click(function(event) {
  event.preventDefault();
//do some processing or whatever here
});

So when a link is clicked the following of the link is stopped, although in HTML the link is clean

1
<a href="http://www.phphow.net">PHPHow.net</a>

PHP best practices #2 – PHP manual is your friend

Posted: December 10th, 2010 | Author: admin | Filed under: PHP | No Comments »

I find PHP manual to be the best PHP resource on the web. It has detailed information about any PHP function, variable, OO, etc. So if you are a beginner and you’re looking for some information about PHP, there are good odds that you’ll find that information in PHP manual. There are also comments about any PHP entity that will help you use that entity easier.


select large data sets from MySQL with mysql_unbuffered_query

Posted: December 9th, 2010 | Author: admin | Filed under: MySQL, PHP | No Comments »

There are situations when you need to select large number of datasets from MySQL, and you can’t use mysql_query function because there’s not enough memory to store the results from MySQL. As we know, mysql_query fetches and buffers all results before you can start processing mysql results. But this won’t work if you have a large amount of results, there won’t be enough memory available to store all the results.

So there is a PHP function, mysql_unbuffered_query, that sends an SQL query to MySQL without fetching and buffering automatically the result rows. This means that you can start working with the first returned row before all rows are returned, so only one row at the time needs to be stored in RAM.

There are some drawbacks using mysql_unbuffered_query:

The easiest way to get all rows is to use mysql_fetch_assoc() until all the rows are retrieved.

1
2
3
4
5
6
7
8
$result = mysql_unbuffered_query("SELECT id FROM yourtable");

while ($row = mysql_fetch_assoc($result))
{

//do something with your $row

}