Using mysql_real_escape_string with sprintf



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?

.



Relevant Pages

  • Re: Attachments to MAPI Message
    ... :> Do this before assigning the attachments to the message. ... :> String, _ ... :> 'is provided for sign-on. ... The default is an empty string. ...
    (microsoft.public.vb.controls.internet)
  • Re: What does this do ? !/somestring/
    ... transliteration)] it is interpreted as a search pattern at run time." ... contains a variable that is set to the empty string. ... because the m/Wor/ match was the last successful pattern match. ...
    (comp.lang.perl.misc)
  • Re: comments of less.rb appreciated
    ... There are no global variables in less.rb. ... ARGV is the command line argument Array. ... Otherwise use an empty string. ...
    (comp.lang.ruby)
  • Re: So whats null then if its not nothing?
    ... > empty string and the absence of a string? ... You have been saying, not I, that you can use the empty string to signify ... NULL covers all data types. ... > that there be a representation for unknown or absent data then that is ...
    (comp.databases.theory)
  • Re: Programming Help Please
    ... empty string rather than a Null value. ... Null value or an empty string, but it may be potentially a little confusing. ... Brendan Reynolds ... >> If IsNull Or IsNull Then ...
    (microsoft.public.access.formscoding)