background image

        die ('Could not connect' . mysql_error());
    mysql_select_db('test', $link);
        
        $col = $_POST['col'];

    $select = "SELECT " . $col . " FROM account_data WHERE account_number = " 
        . $_POST['account_number'] . ";" ;
    echo '<p>' . $select . '</p>';

    $result = mysql_query($select) or die('<p>' . mysql_error() . '</p>');

    echo '<table>';
    while ($row = mysql_fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $row[$col] . '</td>';
        echo '</tr>';
    }
    echo '</table>';

    mysql_close($link);

}
?>

</body>
</html>[/php]

 

因此,要形成保护数据库的习惯,请尽可能避免使用动态 SQL 

 

代码。如果无法避免动态 SQL 代码,请不

 

要对列直接使用输入。清单 4 显示了除使用静态列外,还可以向帐户编号字段添加简单验证例程以确保输

入值不是非数字值。

 

清单 4. 

 

通过验证和 mysql_real_escape_string() 提供保护

[php]                
<html>

<head>
<title>SQL Injection Example</title>

</head>
<body>

<form id="myFrom" action="<?php echo $_SERVER['PHP_SELF']; ?>"
    method="post">
<div><input type="text" name="account_number"
    value="<?php echo(isset($_POST['account_number']) ? 
        $_POST['account_number'] : ''); ?>" /> <input type="submit"
    value="Save" name="submit" /></div>

</form>
<?php

function isValidAccountNumber($number) 
{
    return is_numeric($number);

}

if ($_POST['submit'] == 'Save') {

    /* Remember habit #1--validate your data! */
    if (isset($_POST['account_number']) &&
    isValidAccountNumber($_POST['account_number'])) {

        /* do the form processing */
        $link = mysql_connect('hostname', 'user', 'password') or
        die ('Could not connect' . mysql_error());