infernus
infernus

Reputation: 15

PHP searchbar not working

I'm trying to create a searchbar that search for the title .. database is working , content showing under searchbar then i search sth , it show me "connection succesfully and then no results .. what's wrong ?

<?php 
include 'header.php';
?>

<h3>Rezultate</h3>
<div class"article-container">
<?php 

  if ($conn->connect_error) 
  {
   die("Connection failed: " . $conn->connect_error);
  }
   else 
  echo "Connected successfully";

        if(isset($_POST['submit-search']))
        {

            $search = mysqli_real_escape_string($conn, $_POST['search']);
            $sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
            $result = mysqli_query($conn, $sql);
          $queryResult = mysqli_num_rows($result);

        if($queryResult >0)
        {
           while ($row = mysqli_fetch_assoc($result))
                echo"<div>
                        <h3>".$row['a_title']."</h3>
                        <p>".$row['a_text']."</p>
                        <p>".$row['a_author']."</p>
                        <p>".$row['a_dat']."</p>
                     </div>";
        }
            else 
            {
                echo "<br>No result!";
            }
        }
?>
</div>

Upvotes: 0

Views: 480

Answers (2)

sam
sam

Reputation: 2984

Your SQL is wrong, when referencing the variable $search in the SQL query. Just change the %search% to %$search%:

$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";

Also, I strongly believe you should consider using Prepared Statements for anything which involves user input.

$search = "%" . $_POST['search'] . "%";
$sql = "SELECT * FROM article WHERE a_title LIKE ?";
if($stmt = $mysqli_prepare($conn, $sql)) {
    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $search);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s Search Result: %s\n", $search);

    /* close statement */
    mysqli_stmt_close($stmt);
}

This will protect you a bit more against SQL Injections.

Upvotes: 3

vincebel
vincebel

Reputation: 132

$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";

Your current query is searching for terms like the string "search". Fix it so it's a PHP variable.

$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";

Upvotes: 0

Related Questions