Gcobani Mkontwana

Gcobani Mkontwana

  • 565
  • 1.9k
  • 407.9k

undefined variable 'searchTerm' using php to search prod name

Apr 17 2023 3:40 PM

Hi Team

I am experience small issue when performing search, on php script i get undefined variable searchTerm' line 19. How do i solve this issue? Also how do make users when seeing retrieve data to use search.php page as new page? The current page its affecting design/.

 

// jquery file


$(document).ready(function() {
    $('#search-form').submit(function(event) {
        event.preventDefault(); // Prevent the form from submitting normally
        var searchQuery = $('#search-input').val(); // Get the user's search query
        $.ajax({
            url: 'search.php', // The PHP script that will handle the search
            type: 'POST',
            data: {
                data: 'search=' + searchQuery,

            },
            success: function(response) {
                // Display the search results on the page
                $('#search-results').html(response);
            },
            error: function() {
                alert('An error occurred while searching. Please try again later.');
            }
        });
    });
});

// php file

<?php
  // Connect to the database
  require_once('dbconn.php');

  // Get the search term from the form
  if (isset($_POST['search'])) {
  $searchTerm = $_POST['search'];
  // rest of your code that uses $searchTerm variable goes here
} else {
  // handle the case where the $_GET['search'] variable is not set
}



  // Prepare the query
  $stmt = $pdo->prepare("SELECT * FROM products WHERE product_name LIKE :searchTerm");

  // Bind the search term to the query
  $stmt->bindValue(':searchTerm', '%'.$searchTerm.'%', PDO::PARAM_STR);

  // Execute the query
  $stmt->execute();

  // Fetch the results
  $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php if (!empty($results)): ?>
  <div class="container">
    <h2>Search Results</h2>
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Product Name</th>
          <th>Description</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Discount</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($results as $result): ?>
          <tr>
            <td><?php echo $result['product_name']; ?></td>
            <td><?php echo $result['product_desc']; ?></td>
            <td><?php echo $result['quantity']; ?></td>
            <td><?php echo $result['unit_price']; ?></td>
            <td><?php echo $result['discount']; ?></td>
            <td><?php echo $result['total']; ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php else: ?>
  <p>No results found.</p>
<?php endif; ?>

 


Answers (4)