Приглашаем посетить
Спорт (www.sport-data.ru)

Sending SQL to MySQL

Previous
Table of Contents
Next

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 (mysqli_query.php; excerpt)
<?php
  if ($db = @mysqli_connect('localhost', 'user',
    'password')) {
    require_once 'stripFormSlashes.inc.php';
    mysqli_select_db($db, 'phrasebook');
    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 (mysql_query.php; excerpt)
<?php
  if ($db = @mysql_connect('localhost', 'user',
    'password')) {
    require_once 'stripFormSlashes.inc.php';
    mysql_select_db('phrasebook', $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.';
  }
?>

Figure 7.2. The HTML input form for Listings 7.3 and 7.4.

Sending SQL to MySQL



Previous
Table of Contents
Next