You are here: Using mysql_real_escape_string with sprintf « All PHP « IT news, forums, messages
Using mysql_real_escape_string with sprintf

Posted by drtebi on 10/24/06 11:55

Hello,

I would like you to check out this little snippet of code and tell me
if I could go wrong with this. Basically, the problem is that I need to
input NULL values when a variable is an empty string. I can't do it
with the normal sprintf and mysql_real_escape_string method as
mentioned on http://us2.php.net/mysql_real_escape_string because I
would have to put quotes around the %s, but then I would get the string
'null' instead of null...

So this is my solution so far:

-------------

function prepvar($var) {
if (empty($var)) {
$var = 'null';
} elseif (ctype_digit($var)) {
$var = (int) $var;
} else {
$var = "'" . mysql_real_escape_string($var) . "'";
}
return $var;
}

$query = sprintf('INSERT INTO contacts VALUES(%s, %s, %s, %s)',
$id,
prepvar($name),
prepvar($phone),
prepvar($interests)
);
mysql_query($query) or die(mysql_error());

-------------

Now all positive integers would become e.g. 4 or 343.

Integers in string form would become '4' or '343', which is no problem
with mysql, it doesn't really care if I quote integers or not even for
an integer field (as far as I know).

Anything 0, false, null, '', array(), or declared variables without a
value will become null. This may not always be wanted, but in my case
that's exactly what I want... I want anything that's empty to be null
in my tables. Any string should still be properly escaped.

Any comments?

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация