PHP & Mysqli Code - Is this code safe for a simple search? I am writing some code to search my database and show results. Is the below code ok and safe enough? new to PHP and Mysqli so really appreciate any help that I can get on this subject. Thanks

&lt;?php

    $conn = mysqli_connect("localhost", "root", "", "tutorial");

    if(mysqli_connect_errno()){
        echo "Failed to connect: " . mysqli_connect_error(); 
    }

    error_reporting(0);

    $output = '';

    if(isset($_GET['q']) &amp;&amp; $_GET['q'] !== ' '){
        $searchq = $_GET['q'];

        $q = mysqli_query($conn, "SELECT * FROM search WHERE keywords LIKE '%$searchq%' OR title LIKE '%$searchq%'") or die(mysqli_error());
        $c = mysqli_num_rows($q);
        if($c == 0){
            $output = 'No search results for &lt;b&gt;"' . $searchq . '"&lt;/b&gt;';
        } else {
            while($row = mysqli_fetch_array($q)){
                $id = $row['id'];
                $title = $row['title'];
                $desc = $row['description'];
                $link = $row['link'];

                $output .= '&lt;a href="' . $link . '"&gt;
                            &lt;h3&gt;' . $title . '&lt;/h3&gt;
                                &lt;p&gt;' . $desc . '&lt;/p&gt;
                            &lt;/a&gt;';
            }
        }
    } else {
        header("location: ./");
    }
    print("$output");
    mysqli_close($conn);

?&gt;
It is not safe, you are completely open to SQL Injection. You need to use prepared statements.

Apart from that:


don't use short variables names (q, c, etc)
don't just echo an error, but actually handle it (if there is no db connection, there is no need to execute queries)
try to reduce your nesting, eg by including guard clauses:


Example of guard clauses:

if(!isset($_GET['q']) || $_GET['q'] == ' '){
    // return, die, etc
}

// perform query

if($c == 0){
    // return, die, etc
}

// handle query output