-1

Below is the 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>

Below is the 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";
    } 
    ?>

What is wrong here? I keep getting an error when trying to search in the database - it says the mysql_num_rows function is deprecated, I don't understand how to replace it.

Thank you

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

1 Answers1

0

Please change your $dbc to use the latest one, either mysqli_* or PDO will do. For now, changing your code:

<?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";
?>

If you are interested, there's also an open source project Converting to MySQLi in GitHub.

And regarding more information about why you shouldn't use mysql_* functions, read Why shouldn't I use mysql_* functions in PHP?

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252