尝试通过PHP&创建搜索栏MySQL的

时间:2015-12-29 18:50:38

标签: php mysql

以下是HTML:

<body>
<p>Search</p>
<form name="form1" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50">
<input type="submit" name="Submit" value="search">

</form>
</body>

以下是PHP:

<?php
    require_once '../database/config.php';

    if(!isset($_POST['search'])) {
        header("Location: ads.index.php");
    }
    $search_sql="SELECT * FROM posts WHERE title LIKE '%" .$_POST['search']."%' OR description LIKE '%".$_POST['search']."%'";
    $result = $dbc->query($search_sql);
    if(mysql_num_rows($result)!=0) {    
    $search_rs=mysql_fetch_assoc($result);
    }

    ?>
    <p>Search Results</p>
    <?php if(mysql_num_rows($result)!=0) {
        do { ?>
    <p><?php echo $search_rs['name']; ?></p>
    <?php   } while ($search_rs=mysql_fetch_assoc($result));
    } else {
        echo "No results found";
    } 
    ?>

这里有什么问题?我在尝试搜索数据库时遇到错误 - 它说mysql_num_rows函数已被弃用,我不知道如何替换它。

谢谢

1 个答案:

答案 0 :(得分:0)

请更改您的$dbc以使用最新的mysqli_*PDO。现在,更改代码:

<?php
  require_once '../database/config.php';

  if (!isset($_POST['search']))
    header("Location: ads.index.php");

  // create the connection object
  $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
  // Don't forget to sanitize your user queries.
  // Here $conn is the connection object I assume. Replace it with yours.
  $_POST['search'] = mysqli_real_escape_string($conn, $_POST['search']);
  $search_sql = "SELECT * FROM `posts` WHERE `title` LIKE '%" . $_POST['search'] . "%' OR `description` LIKE '%".$_POST['search']."%'";
  // change the result here.
  $result = mysqli_query($conn, $search_sql);
  if(mysqli_num_rows($result) > 0) {    
    $search_rs = mysqli_fetch_assoc($result);
  }

  ?>
  <p>Search Results</p>
  <?php
  if (mysqli_num_rows($result) > 0) {
    do { ?>
      <p><?php echo $search_rs['name']; ?></p>
  <?php
    // Kindly note, how false and assignment is used here.
    } while (false != ($search_rs = mysqli_fetch_assoc($result)));
  }
  else
    echo "No results found";
?>

如果您有兴趣,GitHub中还有一个开源项目Converting to MySQLi

有关您不应使用mysql_*功能的原因的详情,请参阅 Why shouldn't I use mysql_* functions in PHP?