I have a working query put together in PHP using sqlsrv functions. I'd like to check whether the query contains any results. If it doesn't, I'd like to echo, "No results found". If there are results, I'd like it to proceed and display them.
I've been trying to use sqlsrv_num_rows to check whether the $result variable contains any rows of data but it echo's "No results found" for everything, even for valid searches. For example, if I type in "EOG" in the form and hit "search", the resulting page says, "No results found". The expected result be 20 rows of "EOG" variants. I'm fairly knew to PHP and sqlsrv and have scoured Stackoverflow but haven't come across something that has worked yet. Any help would be appreciated.
Here's the forms section where the user enters his/her search:
<form action="searchResults.php" method="POST" autocomplete="off">
<input type="text" class="form-control" name="opname" placeholder="Search Text">
<button type="submit" name="submit-search">Search</button>
</form>
Here's the PHP where the form input data is received:
<?php
if (empty($_POST['opname'])) {
echo "Nothing was entered in the input field";
} else {
$params = array("%$_POST[opname]%");
$query = "SELECT TOP 20 EntityName
FROM Well
LEFT JOIN Entity ON Entity.PKey = Well.Operator
WHERE EntityName LIKE ?;";
$result = sqlsrv_query($conn, $query, $params);
if (sqlsrv_num_rows($result) == 0) {
echo "No results found";
} else {
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)) {
echo $row[0]."<br />";
}
}
sqlsrv_free_stmt($result);
}
?>