on May 17th, 2008Secure your mysql_* in two minutes

If you’re still using the mysql_* functions in php instead of PDO or some other more advanced db library (propel, doctrine) there’s one big favour you can do yourself, stop using mysql_query() and use this function instead:

<?php
function mysql_squery ($sql) {
	$args = array_slice(func_get_args(), 1);
	$args = array_map('mysql_sescape', $args);
	return mysql_query(sprintf($sql, $args));
}

function mysql_sescape ($value) {
	if (is_string($value)) {
		$value = mysql_real_escape_string($value);
	}
	return $value;
}

Usage is very simple, here are a couple of demo statements:

// Inserting a row
$name = "Fredrik";
$age = 23;
mysql_squery("insert into users (name, age) values('%s', '%s')", $name, $age);

// Updating a row
$name = "Fredrik Holmström";
$id = 1;
mysql_squery("update users set name = '%s' where id = %s", $name, $id);

// Selecting 10 users
$query = mysql_squery('select * from users limit %s, %s', 0, 10);
while($row = mysql_fetch_assoc($query)) {
    echo $row['name'];
}

// Deleting a row
$id = 2;
mysql_squery('delete from users where id = %s', $id);

This will make your SQL-queries a lot more secure vs. something called SQL injections.

One Response to “Secure your mysql_* in two minutes”

  1. Michael Dingleron 19 Jun 2008 at 3:52 pm

    Hmm, wouldn’t you need call_user_func_array for the sprintf?

Trackback URI | Comments RSS

Leave a Reply