0

Error: Notice: Undefined index: search in ... on line 6

PHP

 <?php
        $connection = @mysqli_connect("localhost","root","","RS");
        if($connection->connect_error){//show error if connection failed
            die("Connection failed: " . $connection->connect_error);
        }
        $sql="SELECT username FROM userinfo WHERE username LIKE '%" . $_POST['search'] . "%';";
        $res=$connection->query($sql);
        while($row=$res->fetch_assoc()){
            echo "<div class='results'><p> Username: <a href='profile.php?user=" . $row['username'] . "'> " . $row['username'] . "</a></p></div>";
        }
        mysqli_close($connection);
    ?>

HTML:

  <form action="search.php" method="post">
    <input type="text" name="search" id="bug">
    <input type="submit" name="submit" value="search" id="rat">
  </form>

I've looked at other answers and do not think they are the same. (Or I am not understanding) The error appears when the page is loaded, but disapears when searching with the form above.

I think the problem is that when the page is loaded it has nothing to search for, but I don't know how to fix this. Making $res equal something by default in the php didnt rid me of the error.

Any help is very appreciated, I am still somewhat to to PHP.

  • 1
    *"I think the problem is that when the page is loaded it has nothing to search for"* - Yup, that's it exactly. You could use `isset()` to check if the value exists before trying to use it. Or you could separate the page which displays the form from the page which handles the form. – David Feb 06 '18 at 01:27
  • or save `$_POST['search']` in a variable `$search` then write something like `if($search != NULL){$sql="...";} else {echo"Enter a valid keyword";}`, also your code is vulnerable to sql injection , use prepare statements instead. – Adern Nerk Feb 06 '18 at 01:39

0 Answers0