【问题标题】:pdo select query wont works with string of letters [duplicate]pdo select 查询不适用于字符串 [重复]
【发布时间】:2016-02-25 20:12:00
【问题描述】:

我的选择查询有点问题。如果我输入一串数字 (int) 并且具有该“用户名”的用户存在,我会得到一个名为 $resultw 的结果。但是,如果我在表单中输入一个带有字母(varchar)的字符串,并且用户在我的数据库中有这个用户名,它就不起作用,我也没有收到任何(错误)消息。那会发生什么?

我的 php:

 if(isset($_POST["submit"])){
    $hostname='localhost';
            $user='root';
            $password='';

            $uinput = $_POST['username'];


    try {
                            $dbh = new PDO("mysql:host=$hostname;dbname=game",$user,$password);

                            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
                             $sql = "SELECT id, email, username 
    FROM user
    WHERE username = $uinput"; // 
      if ($resi = $dbh->query($sql)) {// need to add this line in your code
          // then after fetchColumn
         $resultw = $resi->fetchAll();
       }

       if($resultw >= 0) {
           //do something

       }
       else {

           echo "The user you are searching for does not exist.\nPlease check your input.";
       }
    }
    catch(PDOException $e) {

        //
    }
        }

不知道是否需要,但 这就是我的表格

<form style="width:100%" data-ajax="false" action="./username.php" method="post">

        <div style="width:100%" class="ui-grid-a">
        <div style="width:75%;padding-left:5%" class="ui-block-a">
        <div>
        <input data-inline="true" type="text" name="username" id="username"/></div></div>
         <div style="width:20%" class="ui-block-b"><div>
        
        <input data-inline="true" type="submit" name="submit" value="Go" class="ui-btn"/>
    </div></div>        
        </div>      
    </form>

我的 foreach 循环:

<?php foreach ($resultw as $keyres => $rowres): ?>  
        <li>
        <a href="ime.php"><?php echo $rowres['username']; ?></a>
        </li>

            <?php endforeach; ?>

【问题讨论】:

  • 您很容易受到sql injection attacks 的攻击,并且您的查询中的$uinput 周围没有引号,这意味着您有语法错误。但是,您应该会遇到错误,因为您已启用异常。您的错误是username=123username=foo 之间的区别。一个是字段到整数的比较,另一个是字段到字段的比较,您几乎可以肯定没有名为 foo 的字段。

标签: php arrays pdo foreach


【解决方案1】:
$sql = "SELECT id, email, username 
FROM user
WHERE username = '$uinput'";

我建议先清理/转义 $uinput 字符串。

【讨论】:

猜你喜欢
  • 2023-03-03
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 2012-05-14
相关资源
最近更新 更多