dongyue8640 2015-02-27 08:37
浏览 30

如何防止奇怪的用户输入破坏查询中的内容?

Is there a good standard solution to deal with characters like ' and " from being used in user inputs on a web platform?

I'm using php for a webpage and if I have, for example, a search bar which have the following query behind it.

$sql = "select * from aTable where aColumn like '%".$searchedKeyword."%'";

If I search for like Greg's icecream the ' will break the script. Also, I'm guessing if I search for something like 1' or ID>0 my script will have a false effect.

What is the common solution here? Do you usually filter away undesired characters, or is there maybe some method or similiar built-in to php?

  • 写回答

1条回答 默认 最新

  • douwei1128 2015-02-27 08:59
    关注

    You can us PDO and prepared statements to prevent SQL injection.

    http://php.net/manual/en/pdo.prepared-statements.php

    $searchedKeyword = "mykeyword";
    
    //Database details
    $db = 'testdb';
    $username = 'username';
    $password = 'password';
    
    //Connect to database using PDO (mysql)
    try {
        $dbh = new PDO('mysql:host=localhost;dbname='.$db, $username, $password);
    } catch (PDOException $e) {
        var_dump("error: $e");
    }
    
    //Prepared SQL with placeholder ":searchedKeyword"
    $sql = "select * from aTable where aColumn like '%:searchedKeyword%'";
    $sth = $dbh->prepare($sql);
    
    //Bind parameter ":searchedKeyword" to variable $searchedKeyword
    $sth->bindParam(':searchedKeyword', $searchedKeyword);
    
    //Execute query
    $sth->execute();
    
    //Get results
    $result = $sth->fetchAll(); //fetches all results where there's a match
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度