【解決方法】PHPを使用してテーブルから製品名を検索する未定義の変数「searchterm」


こんにちはチーム

小さな問題が発生しています。検索を実行していますが、現在の問題はスクリプト ファイルです。 19 行目の未定義変数 searchTerm。結果は取得されます。 この問題を解決して、検索が呼び出されたときに結果を取得し、データが取得されたときに新しいウィンドウが表示されるようにするにはどうすればよいですか?

私が試したこと:

PHP
<pre><?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: ?>

結果が見つかりません。

//jqueryファイル

<pre lang="Javascript">$(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.');
            }
        });
    });
});

// html コード

HTML
<pre>            <div id="search-not-mobile" class="navbar-collapse collapse">
    <form class="navbar-form" action="search.php" id="search-form" method="POST">
        <div class="input-group">
            <input type="text" placeholder="Search....." class="form-control" id="search-input" name="search">

            <div class="input-group-btn">
                <button type="submit" class="btn btn-primary" id="search-button">
                    
                </button>
            </div>
        </div>
    </form>
</div>
<div id="search-results"></div>

解決策 1

おそらく、それは if...else その上:

PHP
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
}

「検索」が設定されていない場合、$searchTerm には値が割り当てられず、存在しません。

の上にデフォルト値の割り当てを追加します if そしてそれはうまくいくはずです。

それを証明するには:

PHP
$x = 2;
if ($x == 3){
    $searchTerm = 'Hello World';
} else {
    // code...
}
echo $searchTerm;

エラーで失敗しますが、次の場合:

PHP
$searchTerm = "DEFAULTED";
$x = 2;
if ($x == 3){
    $searchTerm = 'Hello World';
} else {
    // code...
}
echo $searchTerm;

正常に動作します。

コメント

タイトルとURLをコピーしました