如果ELSE语句在while循环中无法正常工作

时间:2015-02-18 16:30:50

标签: php if-statement

在我的while循环中,我能够正确地执行if语句的第一部分,但是ELSE将无法正常工作,我可以使一切正常工作,所以我得到了字符串,我将它与数据库中的字符串相匹配如果字符串是正确的,我也得到正确的输出,但如果字符串不匹配,我不能让else语句工作,所以只是回显出字符串不匹配。

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!";
        }

    }

} 

}

这是表格:

<form action="search.php" method="post">

    <p>
        <input type="text" name="search_query" id="search" />
        <input type="submit" name="submit" value="SEARCH" />
    </p>

</form>

1 个答案:

答案 0 :(得分:1)

您的查询返回$ search_query与client_id匹配的结果,这意味着if / else语句的“else”部分永远不会应用。你需要将它移到while循环之外。

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
    }
}