提问者:小点点

我正在尝试使用php创建一个搜索框。但是,当我搜索代码时,它不起作用


<div class="row">
                <?php
                $connection = mysqli_connect('localhost','root','','product-store');
                if(isset($_POST['search'])) {
                    $searchKey = $_POST['search'];
                     $sql = "SELECT * FROM products WHERE code_no LIKE '%$searchKey%'";


                } else {


                    $sql = "SELECT * FROM products order by code_no desc";
                    $searchKey = "";


                }

            ?>
            <form action="tabledata.php" method="POST"> 
                <div class="col-md-12 col-sm-12 col-xs-12">
                    <input type="text" name="search" class="form-control" placeholder="Search By Code" value="<?php echo $searchKey; ?>" > 
                </div>
                <br>
                <div class="input-group">
                    <button class="btn btn-success">Search</button>
                </div>
                <br>
            </form>

            <br>
            <br>

            </div>



        </div>
    </div>
</div>

共2个答案

匿名用户

您在输入字段中缺少id

<input type="text" id="search"  name="search" class="form-control" placeholder="Search By Code" value="<?php echo $searchKey; ?>" >

匿名用户

您不仅在输入字段中丢失了id,而且您也从未在php代码中执行查询并获取结果。sql注入是可能的,请清理您的$search chKey或使用准备好的语句。

也许您还可以将搜索查询放在不同的php文件中,并在那里创建html,返回ajax函数。

也许这会有所帮助:

为ajax搜索功能创建一个新的php文件,如searchData。php

    <?php //searchData.php

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['query'])) {
  $connection = mysqli_connect('localhost','root','','product-store');

  $searchKey  = $_POST['query']; // Needs to be sanitized to prevent sql injections
  $sql   = mysqli_query($connection, "SELECT * FROM products WHERE code_no LIKE '%$searchKey%'");

  if (mysqli_num_rows($sql) > 0) {
    // Fetch the rows
    $rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);

    $html = '';
    // Loop through all the rows
    foreach ($rows as $row) {
      // Create here your html you want to return to your ajax function
    }

    echo $html;

  } else {
    // No results, echo html/ text to the ajax function to inform the user
  }
}

将ajax函数中的url更改为search chData.phpajax函数将获得该文件中所有的text/html