dongqiang5865 2013-06-04 22:51
浏览 109
已采纳

将SQL转换为PDO以防止SQL注入[重复]

This question already has an answer here:

I am still new to php and MySQL as far as development is concerned. I would love some advice to make sure I am doing everything correctly. I have one page that I believe is converted the correct way and one page that I need to convert.

Here is the one that I have setup is this correct?

<?php $title = 'SEARCH'; $page = '';include 'includes/header.php';?>

<body>

<?php include 'includes/nav.php'; ?>

<?php
$q = $_GET['q'];

// CONNECT TO THE DATABASE
$DB_NAME = 'code_storage';
$DB_HOST = 'localhost';
$DB_USER = 'user';
$DB_PASS = 'pass';

try {
    $dbcon = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME", $DB_USER, $DB_PASS);
    //echo 'Connected to database';

    $sql = <<<SQL
    SELECT * 
    FROM snippets
    WHERE CODE_NAME LIKE '%$q%' OR
    CODE_DESC LIKE '%$q%' OR
    CODE_TAGS LIKE '%$q%' OR
    CODE_USAGE LIKE '%$q%'
 SQL;
    echo '<div class="row">';
    echo    '<div class="panel">';
        printf("Your search for <b>$q</b> returned %d records.
", $dbcon->query($sql)->rowCount());
    echo    '</div>';
    echo '</div>';

    foreach ($dbcon->query($sql) as $row) {
        //print $row['CODE_NAME'] . '<br/>' . "
";
        echo '   <div class="row">' . "
";
        echo '       <div class="large-12 columns">' . "
";
        echo '              <b><a href="results.php?id=' . $row['_ID'] . '">' . $row['CODE_NAME'] . '</a></b><br/><br/>' . "
";
        echo '       </div>' . "
";
        echo '   </div>' . '<br/><br/>' . "
";
    }


    $dbcon = null;
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
 ?>
<?php include 'includes/footer.php';?>

And here is the one I still need to convert this is the once I could really use some help with

<?php

// CONNECT TO THE DATABASE
$DB_NAME = 'code_storage';
$DB_HOST = 'localhost';
$DB_USER = 'user';
$DB_PASS = 'pass';


$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

// Fix for the ' and " 

$_POST['name'] = $mysqli->real_escape_string($_POST['name']);
$_POST['desc'] = $mysqli->real_escape_string($_POST['desc']);
$_POST['usage'] = $mysqli->real_escape_string($_POST['usage']);
$_POST['code'] = $mysqli->real_escape_string($_POST['code']);
$_POST['tags'] = $mysqli->real_escape_string($_POST['tags']);

$sql = <<<SQL
    INSERT 
    INTO snippets
    (CODE_NAME,CODE_DESC,CODE_USAGE,CODE_SYNTAX,CODE_TAGS)
    VALUES
    ('$_POST[name]', '$_POST[desc]', '$_POST[usage]', '$_POST[code]', '$_POST[tags]');
SQL;

if(!$result = $mysqli->query($sql)){
    echo '<br/><br/><br/><br/>' . "
";
    echo '<div class="row">' . "
";
    echo '  <div class="large-12 columns">' . "
"; 
    echo '      <div data-alert class="alert-box alert">' . "
";
    echo '          There was an error' . "
";
    echo '          <a href="../site/upload.php" class="close">&times;</a>' . "
";
    echo '      </div>' . "
";
    echo '  </div>' . "
";
    echo '</div>' . "
";
    echo '<br/><br/><br/><br/>' . "
";
    echo '<div class="row">' . "
";
    echo '  <div class="large-12 columns">' . "
";
    die('There was an error with the code [' . $mysqli->error . ']');
    echo '  </div>' . "
";
    echo '</div>' . "
";

}
    echo '<br/><br/><br/><br/>' . "
";
    echo '<div class="row">' . "
";
    echo '  <div class="large-12 columns">' . "
"; 
    echo '      <div data-alert class="alert-box success">' . "
";
    echo '          Code Successfully Added' . "
";
    echo '          <a href="../site/" class="close">&times;</a>' . "
";
    echo '      </div>' . "
";
    echo '  </div>' . "
";
    echo '</div>' . "
";
    echo '<br/><br/><br/><br/>' . "
";
*/

?>

*EDIT* Here is what I have so far but it doesn't seem to be returning any records any ideas why?

 $q = $_GET['q'];

$DB_NAME = 'code_storage';
$DB_HOST = 'localhost';
$DB_USER = 'user';
$DB_PASS = 'pass';


$dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db = new PDO($dsn, $DB_USER, $DB_PASS);

$query = "SELECT * FROM `SNIPPETS` WHERE `CODE_NAME` LIKE :name OR `CODE_DESC` LIKE :name OR `CODE_TAGS` LIKE :name OR `CODE_USAGE` LIKE :name";
$prep = $db->prepare($query);
$prep->execute(array(":name" => "%" . $q . "%"));

echo '<div class="row">';
    echo    '<div class="panel">';
       printf("Your search for <b>$q</b> returned %d records.
", $prep->rowCount());
    echo    '</div>';
echo '</div>';

while ($row = $prep->fetch()) {
    echo '   <div class="row">' . "
";
    echo '       <div class="large-12 columns">' . "
";

    echo             $row['CODE_NAME'] . '<br/><br/>' . "
";
    echo             $row['CODE_DESC'] . '<br/><br/>' . "
";
    echo             $row['CODE_USAGE']. '<br/><br/>' . "
";
    echo '       </div>' . "
";
    echo '   </div>' . '<br/><br/>' . "
"; 


}

$db = null;

I have found out that I am getting this error

Connection failed: SQLSTATE[HY093]: Invalid parameter number: number of bound    variables does not match number of tokens
</div>
  • 写回答

1条回答 默认 最新

  • dongmei1911 2013-06-05 17:14
    关注

    Unfortunately, some versions of PDO don't know how to use a named parameter multiple times in the same query. If I recall, this bug is fixed in newer versions, but you may be stuck using an older version of PHP with PDO.

    One workaround is this:

    $query = "SELECT * FROM `SNIPPETS` WHERE `CODE_NAME` LIKE :name1 
      OR `CODE_DESC` LIKE :name2 
      OR `CODE_TAGS` LIKE :name3 
      OR `CODE_USAGE` LIKE :name4";
    $prep = $db->prepare($query);
    $qpattern = "%" . $q . "%";
    $prep->execute(array(":name1" => $qpattern, ":name2" => $qpattern, ":name3" => $qpattern, ":name4" => $qpattern));
    

    Or else use positional parameters instead of named parameters:

    $query = "SELECT * FROM `SNIPPETS` WHERE `CODE_NAME` LIKE ? 
      OR `CODE_DESC` LIKE ? 
      OR `CODE_TAGS` LIKE ? 
      OR `CODE_USAGE` LIKE ?";
    $prep = $db->prepare($query);
    $qpattern = "%" . $q . "%";
    $prep->execute(array_fill(0, 4, $qpattern));
    

    PS: Not related to your question about using prepared statements, but your use of '%pattern%' for full-text search is thousands of times slower than using any fulltext index solution.


    Another good habit is to check for errors after every call to PDO::prepare() or PDOStatement::execute(). Either enable exception mode, or else check the return values for false:

    if (($prep = $db->prepare(...)) === false) {
      // check $db->errorInfo() for details
    }
    if ($prep->execute(...) === false) {
      // check $prep->errorInfo() for details
    }
    

    Checking for errors is also a best practice for the old mysql API, and the mysqli API.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题