php - if ELSE statement not working correctly in while loop

In my while loop I am able to correctly do the first part of the if statement but the ELSE will not work, I can get everything to work correctly so I get the string and I match it against the string in the db and if the string is correct I get the correct output too but if the string does not match I can't get the else statement to work so to just echo out that the string does not match.
if(isset($_POST['submit'])) {
$search_query = escape_string($_POST['search_query']);
$query = "SELECT client_id, client_name, status FROM clients WHERE client_id = '".$search_query."' ";
$result = mysqli_query($connection, $query);
if($result && !empty($search_query)) {
while($code = mysqli_fetch_assoc($result)) {
if($_POST['search_query'] === $code['client_id']) {
echo $code['client_name'] . " " . $code['client_id'] . " " . $code['status'];
} else {
echo $_POST['search_query'] . " ID does not exist!";
}
}
}
}
This is the form:
<form action="search.php" method="post">
<p>
<input type="text" name="search_query" id="search" />
<input type="submit" name="submit" value="SEARCH" />
</p>
</form>
Answer
Solution:
Your query returns results where $search_query matches client_id, which means that the "else" part of your if/else statement never applies. You need to move it outside of the while loop.
if ( isset($_POST['submit']) ) {
// By default there is no match
$match = false;
$search_query = escape_string($_POST['search_query']);
if ( !empty($search_query) ) { // Why query in the first place if the search is empty?
$query = "SELECT client_id, client_name, status FROM clients WHERE client_id = '".$search_query."' ";
$result = mysqli_query($connection, $query);
if ( $result ) {
while ( $code = mysqli_fetch_assoc($result) ) {
// Store the matched data in an array so that is is easy to work with
$match = array(
'client_name' => $code['client_name'],
'client_id' => $code['client_id'],
'status' => $code['status']
);
}
}
}
if ( is_array($match) ) {
// match found
} else {
// match not found
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: to enable extensions, verify that they are enabled in your .ini files
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.