当输入变量超过1个字符时,为什么我得不到任何结果?

时间:2017-11-30 14:27:30

标签: php sql

所以这应该是歌曲的搜索领域。当我搜索像“o”这样的单个字符时,结果是在任何位置都带有字母“o”的歌曲。例如,当我搜索多个像“oo”这样的字符时,我根本没有得到任何结果,即使我在标题中有“oo”的歌曲。

<?php
include 'conn.php';

if (isset($_POST['submitsearch'])){
    $search=$_POST['search'];
    $query2 = "select * from songs where Title LIKE '%".$search."%'";

    $result2 = mysqli_query($connection, $query2);

    $row = mysqli_fetch_array($result2, MYSQLI_ASSOC);
    while($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
      echo $row['Title'];
    }
}

1 个答案:

答案 0 :(得分:4)

可能你只有一行oo。您的代码将始终松散结果集的第一行,因为您在while循环中获取OutSide。

尝试没有这样的

<?php
include 'conn.php';

if (isset($_POST['submitsearch'])){
    $search=$_POST['search'];
    $query2 = "select * from songs where Title LIKE '%".$search."%'";

    $result2 = mysqli_query($connection, $query2);

    // gets first row and then does nothing with it
    //$row = mysqli_fetch_array($result2, MYSQLI_ASSOC);
    while($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
      echo $row['Title'];
    }
}
  

您还应该知道您的脚本存在SQL Injection Attack的风险   甚至if you are escaping inputs, its not safe!   使用prepared parameterized statements