Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, November 06, 2009

Checking for empty variables in PHP

While writing some php code I checked for an empty string, using the empty() function, but I got this error :

PHP Fatal error:  Can't use method return value in write context
I found this very strange because I've used the empty() function many times before. It turns out that the empty() function can not handle the return value of a function or method. You can only check variables using this function.

The solution is simple, store the return value of a function in a variable, and then check the variable with the empty() function :

wrong
if ( empty ( some_function() ) ) {

right
$some_variable = some_function();
if ( empty ( $some_variable ) ) {



On a side note, using the empty() function, is the best way to check for an empty variable, because it combines multiple checks, and works for different variable types. See documentation for details. When relying solely on strlen() or isset(), you can get an unexpected result.

Wednesday, March 11, 2009

Rename multiple tables in MySQL database

Having to rename multiple tables with a similar pattern (prefix, suffix, ...) by replacing the recurring pattern, isn't an easy task, because there is no simple function or statement for doing it, not as far as I know.
Renaming tables like 'table_1234' and 'table_3456' to 'new_table_1234' and 'new_table_3456', is pretty straightforward in SQL:


RENAME TABLE `database`.`table_1234`
TO `database`.`new_table_1234`;
RENAME TABLE `database`.`table_3456`
TO `database`.`new_table_3456`;

or in one SQL statement :

RENAME TABLE
`database`.`table_1234` TO `database`.`new_table_1234`,
`database`.`table_3456` TO `database`.`new_table_3456`;

But when renaming a lot of tables, this method becomes tedious and time consuming.

This PHP script automates the renaming of multiple tables in a MySQL database. It lists all tables in a MySQL database, which contain a defined string pattern. The script creates and executes a series of SQL statements, which rename the table by replacing the search pattern in the original table name with another pattern in the new table name.

This script can easily be modified to rename multiple databases, or when stripping the original pattern (f.e. a prefix) and adding a new pattern (f.e. a suffix) is needed.

<?php
$db_server = "localhost"; // hostname MySQL server
$db_username = "username"; // username MySQL server
$db_password = "password"; // password MySQL server
$db_name = "database"; // database name

$pattern = "pattern_"; // search string
$new_pattern = "new_pattern_"; // replacement string,
// can be empty

// login to MySQL server
$link = mysql_connect( $db_server, $db_username, $db_password);

if (!$link)
{
die('Could not connect: ' . mysql_error());
}

// list all tables in the database containing the search pattern
$sql = "SHOW TABLES FROM `" . $db_name . "`";
$sql .= " LIKE '%" . $pattern . "%'";

$result = mysql_query ( $sql, $link );
if (!$result)
{
die("Invalid query: " . mysql_error( $link ));
}

$renamed = 0;
$failed = 0;

while ( $row = mysql_fetch_array ($result) )
{
// rename every table by replacing the search pattern
// with a new pattern
$table_name = $row[0];
$new_table_name = str_replace ( $pattern, $new_pattern, $table_name);

$sql = "RENAME TABLE `" . $db_name . "`.`" . $table_name . "`";
$sql .= " TO `" . $db_name . "`.`" . $new_table_name . "`";

$result_rename = mysql_query ( $sql, $link );
if ($result_rename)
{
echo "Table `" . $table_name . "` renamed to :`";
echo $new_table_name . "`.\n";
$renamed++;
}
else
{
// notify when the renaming failed and show reason why
echo "Renaming of table `" . $table_name . "` has failed: ";
echo mysql_error( $link ) . "\n";
$failed++;
}
}

echo $renamed . " tables were renamed, " . $failed . " failed.\n";

// close connection to MySQL server
mysql_close( $link );
?>

Syntax Highlighting in Blogger

I've added some Javascript to the template of my blog to get Syntax Highlighting working. This means source code is formatted so it is easier to read. If it works allright, you should see an example of some highlighted php-code below. (The source code is not formatted/coloured when reading this post through an RSS-feed.)


<?php
/* Sample php code
This code doesn't do anything at all.
It just contains some php elements that should be formatted
and coloured.
*/

$some_variable = "some_string";

// Some comment
$result = some_function( $some_variable );

if (!$result)
{
die("It doesn't work!");
}

$some_array = new array();

$some_array[0] = $result;
?>

Wednesday, July 16, 2008

Todo list

This post is a work in progress, listing things I would like to do in the near and more distant future.
Some may be completed soon, while others will take a long time or may never be completed.
While some items are in preparation of another item on the list, others have no set goal or defined purpose, yet. Thus, the items on this list are in no particular order :

  • Learning new programming languages and improving my knowledge of the ones I'm already familiar with :
  • Linux :

    • Finish the CLFS project for my old 486

    • Upgrade to a new version of LFS on my server

    • Get my encrypted external hard drive working in linux and windows

    • Learn more about the linux kernel and maybe participate in its development or that of another Open Source project

  • Continue work on some small PHP-projects

  • Think about the feasibility of the semantic web, Turing tests, universal machines and time travel.

  • (Re)paint my bathroom

  • Find a new hobby

  • Get a girlfriend

Sunday, August 19, 2007

My programming personality type : DHSB

You're a Doer.
You are very quick at getting tasks done. You believe the outcome is the most important part of a task and the faster you can reach that outcome the better. After all, time is money.


You like coding at a High level.

The world is made up of objects and components, you should create your programs in the same way.


You work best in a Solo situation.

The best way to program is by yourself. There's no communication problems, you know every part of the code allowing you to write the best programs possible.


You are a liBeral programmer.

Programming is a complex task and you should use white space and comments as freely as possible to help simplify the task. We're not writing on paper anymore so we can take up as much room as we need.


I came along this programmer personality test on the blog of Jan, an old classmate.

Saturday, August 18, 2007

Google Gears


Some time ago (31st of May 2007), Google Gears was launched. Yet another new project, next to all the other applications Google has launched already.
But this one is different. It's not a stand-alone application, like Gmail or Google Analytics, but a framework that makes it possible to store a website or a web application offline, so you can still visit this website or use this web application while you are not connected to internet.

To show what the framework does, a new feature was implemented for Google Reader, an online news feed (RSS/Atom) reader, that makes it possible to read newsfeeds while offline. This feature uses the Google Gears framework.

I've used it for a while now, and I must say that it works well. When I'm traveling by train for example, I switch to offline mode in Google Reader, before I leave home.
When going to offline mode, Google Reader downloads 2000 messages and stores them locally. On the train, I open Google Reader in my browser and start reading the news messages, just like I would when connected to the internet.
When I get back home and switch back to online mode, Google Reader synchronises with the online version. All messages I read offline, are marked as read and the starred or shared messages are set.

I'm wondering which Google applications will be next to have an offline mode, using the Google Gears technology. An offline version of Google Calendar would be nice. ;-)

Saturday, May 05, 2007

md5-hash of strings are not the same with different charactersets

I maintain a website which hosts a forum, using popular forum software. This forum stores an md5-hash of the passwords of the users of this forum in a database. This website also has an admin section which is protected by a password. The passwords of the forum database are used to get access to the admin section. To do this the md5-hash of the submitted password is compared with the md5-hash stored in the database, exactly the same way as it is done by the forum software.

This week one of the users of the website reported to me that he was unable to access the admin section, but was still able to log in to the forum. The mechanism to check the password is identical for the admin section and the forum (as described in the previous paragraph), so at first I didn't understand why he couldn't access the admin section of the website. After some debugging I found out that the md5() function produced a different hash of the same password. It produced a correct hash, which was identical to the hash stored in the database, on the forum, but a different hash came up on the admin section.

I then remembered that the webserver (Apache 1.3) was upgraded a week earlier. The new webserver (Apache 2.0) uses a different default characterset (UTF-8), causing the website to work perfectly, but some special characters were replaced with question marks. This problem was solved by changing the characterset, in a .htaccess file in the directory of the forum, as the problem only occured there :

In .htaccess I added:

AddDefaultCharset ISO-8859-1

Only the forum used the old characterset, while the rest of the website, including the admin section, used the new default characterset of the webserver. Everything seemed to work fine.

Until this week, when that user couldn't access the admin section, while some other users still could login to the admin section. After some investigation I found out that the user that couldn't login used some special characters in his password. Then I started to realise that the md5() function must produce a different hash of the same string when it is encoded in a different characterset.
This makes perfect sense. In a lot of charactersets, normal alphanumeric characters (a-z, A-Z, 0-9) are in the same place, but some special characters like é or @, can have a different place in another characterset. When a string encoded in different charactersets contains special characters, it has a different value (on a binary/hexadecimal level). Thus when a hash is calculated of these strings, different hashes are produced.

Now that I understood what was happening I solved the problem by applying the same characterset to the entire website. The user who reported the problem was again able to login to the admin section.