0

I like this code found here Do you guys think, that on this query can be implemented prepared statement to prevent SQL injection?

<?php
    $conn = mysqli_connect("localhost", "root", "", "blog_samples");    
    $keyword = "";  
    $queryCondition = "";
    if(!empty($_POST["keyword"])) {
        $keyword = $_POST["keyword"];
        $wordsAry = explode(" ", $keyword);
        $wordsCount = count($wordsAry);
        $queryCondition = " WHERE ";
        for($i=0;$i<$wordsCount;$i++) {
            $queryCondition .= "title LIKE '%" . $wordsAry[$i] . "%' OR description LIKE '%" . $wordsAry[$i] . "%'";
            if($i!=$wordsCount-1) {
                $queryCondition .= " OR ";
            }
        }
    }
    $orderby = " ORDER BY id desc"; 
    $sql = "SELECT * FROM links " . $queryCondition;
    $result = mysqli_query($conn,$sql); 
?>
<?php 
    function highlightKeywords($text, $keyword) {
        $wordsAry = explode(" ", $keyword);
        $wordsCount = count($wordsAry);

        for($i=0;$i<$wordsCount;$i++) {
            $highlighted_text = "<span style='font-weight:bold;'>$wordsAry[$i]</span>";
            $text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
        }

        return $text;
    }
?>

The problem here is that this code explode keywords by space

$wordsAry = explode(" ", $keyword);

So I dont know how many prepared statements will It be.. Maybe in such query prepared statement is useless or imposible to implement. Or am I wrong? Or maybe I can prevent SQL injection with preg_replace in this case, or what can I do here to prevent SQL injection?

Zdenek Slavik
  • 142
  • 3
  • 13

0 Answers0