1
\$\begingroup\$

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

<?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']) && $_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 <b>"' . $searchq . '"</b>';
        } else {
            while($row = mysqli_fetch_array($q)){
                $id = $row['id'];
                $title = $row['title'];
                $desc = $row['description'];
                $link = $row['link'];

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

?>
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Thanks. I am new to PHP and Mysqli and basically learning form youtube as I have no idea where to learn the basics for coding a search box. I don't want a career in coding so need to learn only what I need to know. Should I just be learning PHP from start to finish?. I would really appreciate some direction or any courses anyone knows about that iwll teach me the idiot guide to PHP and Mysqli.? \$\endgroup\$
    – Bill04
    Jan 4 '17 at 16:27
  • \$\begingroup\$ Any advice on how to learn how to avoid the security issues. I really would like to learn the search / results part of PHP but really dont know where to start. Any advice appreciated. \$\endgroup\$
    – Bill04
    Jan 4 '17 at 21:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.