表单输入中的数组-选择语句MySQLi参数化

时间:2019-11-10 16:40:34

标签: php mysqli sql-injection

将在Form输入中输入的短语转换为数组,以使用MySQLi传递到MySQL select语句where子句。我已经实现了php代码,但是我无法锻炼如何对查询进行参数设置以防止sql注入攻击。我在这个网站上看了几个问题,但是我很难将其与我的代码联系起来。

if(!empty($_POST['Message']))
{
      $searchStr = get_post($con,'Message');
      $aKeyword = explode(" ", $searchStr);

      $query ="SELECT m.ID, m.MessageText FROM MessageMain m LEFT OUTER JOIN Likes l on m.ID = l.PostID WHERE MessageText LIKE '%" . $aKeyword[0] . "%'";

     for($i = 1; $i < count($aKeyword); $i++) {
        if(!empty($aKeyword[$i])) {
            $query .= " OR MessageText like '%" . $aKeyword[$i] . "%'";
        }
      }

      $query .= " GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc";

       $result = $con->query($query);
       $rowcount=mysqli_num_rows($result);

1 个答案:

答案 0 :(得分:2)

如果您想根据要匹配的关键字数动态构建WHERE子句,则可以这样做:

if (!empty($_POST['Message'])) {
    $searchStr = get_post($con, 'Message');
    $aKeyword = explode(" ", $searchStr);

    $whereClauseArr = [];
    foreach ($aKeyword as $keyword) {
        if ($keyword) {
            $whereClauseArr[] = "MessageText LIKE ?";
            $whereValues[] = '%'.$keyword.'%';
        }
    }

    $stmt = $con->prepare(
        'SELECT m.ID, m.MessageText 
        FROM MessageMain m 
        LEFT OUTER JOIN Likes l on m.ID = l.PostID 
        WHERE '.implode(' OR ', $whereClauseArr).'
        GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc'
    );

    $stmt->bind_param(str_repeat('s', count($whereValues)), ...$whereValues);
    $stmt->execute();
    $result = $stmt->get_result();
}

尽管在您的情况下,使用多个正则表达式检查同一列是否具有多个值可能会更好。根据您拥有的关键字数量,这将使您的查询更简单,也可能更快。

if (!empty($_POST['Message'])) {
    $searchStr = get_post($con, 'Message');
    $aKeyword = explode(" ", $searchStr);

    $aKeyword = array_filter($aKeyword); // Remove empty values

    $stmt = $con->prepare(
        'SELECT m.ID, m.MessageText 
        FROM MessageMain m 
        LEFT OUTER JOIN Likes l on m.ID = l.PostID 
        WHERE MessageText REGEXP ?
        GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc'
    );

    $regexString = implode('|', $aKeyword);
    $stmt->bind_param('s', $regexString);
    $stmt->execute();
    $result = $stmt->get_result();
}