In the php manual:
http://www.php.net/manual/en/function.mysql-real-escape-string.php

The following method is suggested:
<?php
// Quote variable to make safe
function quote_smart($value)
{
  // Stripslashes
  if (get_magic_quotes_gpc()) {
      $value = stripslashes($value);
  }
  // Quote if not a number or a numeric string
  if (!is_numeric($value)) {
      $value = "'" . mysql_real_escape_string($value) . "'";
  }
  return $value;
}

// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
  OR die(mysql_error());

// Make a safe query
$query = sprintf("SELECT * FROM users WHERE user=%s AND password=%s",
          quote_smart($_POST['username']),
          quote_smart($_POST['password']));

mysql_query($query);
?>

What is the purpose of the sprintf? If it were using %d on integers I
could see the point, but as we're talking about %s strings, what is
the advantage to using sprintf? How does this differ from:
$query = "SELECT * FROM users WHERE user=".$_POST['username']." AND
password=".$_POST['password'];

Dotan Cohen
http://linux-apache-mysql-php.org
23

Reply via email to