Jake
Jake

Reputation: 11

PHP SQL search not returning any results

I'm trying to make a search bar to search my db but it always returns 0 results,

Here is the Connect and search code,

<?php
  $serverName = "server";
  $connectionInfo = array( "Database"=>"server");
  $conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
    echo "Connection established.<br />";
  }else{
    echo "Connection could not be established.<br />";
    die( print_r( sqlsrv_errors(), true));
  }

  $output ='';

  if(isset($_POST['PartSelect'])){
    $searchq = $_POST['PartSelect'];
    $query = sqlsrv_query($conn, "SELECT * FROM Parts WHERE PartNumber LIKE '%$searchq%'") or die ("Could not search");
    $count = sqlsrv_num_rows($query);
    if($count == 0){
      $output = 'There are no results';

----- This Section is new error Code -----

            $rows = sqlsrv_has_rows( $query );
      if ($rows === true)
        echo "\nthere are rows\n";
     else
        echo "\nno rows\n";

---- End Section ------ This prints saying it has rows so it it picking up the data,

}
    else {
      while ($row = sqlsrv_fetch_array($query)){
        $Partno = $row['PartNumber'];
        $output .= '<div>'.$PartNo. '</div>';
      }
 }
      ?>

Here is the search bar and submit button (I am using materialize as a framework), and the output at the end.

<form action="Tests.php" method="post">
    <div class="form-group">
      <br/><input name="PartSelect" type="text" class="form-control" id="PartSelect" aria-describedby="nameHelp" placeholder="Enter Part">
      <br/><button name="SelectPartbtn" id="Submitbtn" type="Submit" class="waves-effect waves-light btn">Find</button>
    </div>

    <?php print ("$output"); ?>

  </form>

Upvotes: 1

Views: 55

Answers (1)

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7161

try with this code check connection is made or not

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = sqlsrv_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . sqlsrv_errors());
}

Upvotes: 1

Related Questions