PHP

Sending SQL to MySQL

mysqli_query()

The functions mysql_query() and mysqli_query() send SQL to a database identified by a handlesecond parameter for mysql_query(), first parameter for mysqli_query(). However, to avoid an attack called "SQL injection" (a method to inject SQL statements using GET or POST data), you absolutely must use mysql_real_escape_string() or mysqli_real_escape_string() to escape any dangerous characters such as single quotes. See the preceding and the following listing for implementations. The code missing from those listings (but, of course, it is included in the code download) is basically an HTML form that accepts a quote, its author, and a year. Figure 7.2 shows the HTML input form for the quote collection.

Sending SQL to MySQLi
<?php
  if ($db = @mysqli_connect('localhost', 'user',
    'password')) {
    require_once 'stripFormSlashes.inc.php';
    mysqli_select_db($db, 'hoshmand');
    mysqli_query($db, sprintf(
      'INSERT INTO quotes (quote, author, year)
         VALUES (\'%s\', \'%s\', \'%s\')',
      mysqli_real_escape_string($db, $_POST
        ['quote']),
      mysqli_real_escape_string($db, $_POST
        ['author']),
      intval($_POST['year'])));
    echo 'Quote saved.';
    mysqli_close($db);
  } else {
    echo 'Connection failed.';
  }
?>

Sending SQL to MySQL
<?php
  if ($db = @mysql_connect('localhost', 'user',
    'password')) {
    require_once 'stripFormSlashes.inc.php';
    mysql_select_db('hoshmand', $db);
    mysql_query(sprintf(
      'INSERT INTO quotes (quote, author, year)
         VALUES (\'%s\', \'%s\', \'%s\')',
      mysql_real_escape_string($_POST['quote'],
        $db),
      mysql_real_escape_string($_POST['author'],
        $db),
      intval($_POST['year'])), $db);
    echo 'Quote saved.';
    mysql_close($db);
  } else {
    echo 'Connection failed.';
  }
?>

The HTML input form for Listings 7.3 and 7.4.

by BrainBellupdated
Advertisement: