【问题标题】:Ain't echo when row doesn't exist in PHP当行在 PHP 中不存在时不回显
【发布时间】:2021-11-13 15:08:57
【问题描述】:
<tr>
    <td id="idtypesectype2">Skype</td>
    <td id="doubledotsec">:</td>
    <td>
        <?php
        $search = $_GET['search']; 
        $sql ="SELECT * FROM contact_info WHERE CU_id='$search' AND contact_information_type='social_media_skype' AND visibility='1'";
        $result = $db -> query($sql);
        WHILE ($row=$result->fetch_assoc()) {
            if(mysqli_num_rows($result) < 0) { 
                echo "-"; 
            } else { 
                echo $row['contact_information']; 
            } 
?><br>
<?php 
        } 
?>
    </td>
</tr>

我不明白 - 当该行为空时,它是一个空白。你能帮我解决这个问题吗?我希望它会显示 - 当该行不存在时。

【问题讨论】:

标签: php html sql


【解决方案1】:

您正在检查查询在您的 while 循环中返回了多少行,您在其中获取单行。然而,如果没有,你永远不会进入 while 循环。 因此,您需要做的就是将 if 条件放在 while 之前,并将 while 循环放在 else 语句中。

首先,您必须记住,没有任何内容可处理的 while 循环只会终止并继续执行其后的代码。所以如果要测试结果集中的行数,需要在运行while循环之前进行

您还需要使用准备好的查询来保护自己免受SQL Injection Attack

    <tr>
        <td id="idtypesectype2">Skype</td>
        <td id="doubledotsec">:</td>
        <td>
<?php
 
    $sql ="SELECT * 
            FROM contact_info 
            WHERE CU_id=? 
            AND contact_information_type='social_media_skype' 
            AND visibility='1'";
    # prepare and bind parameter to the query to protect against SQL Injection
    $stmt = $db->prepare($sql);
    $stmt->bind_param('i', $_GET['search']);
    $stmt->execute();

    $results = $stmt->get_result();

    if($result->num_rows == 0) { 
        echo "-";  
    }
    
    while ($row=$result->fetch_assoc()) {
        echo $row['contact_information']; 
    } 
?>
<br>
    </td>
</tr>

【讨论】:

    【解决方案2】:

    我认为您必须将代码更改为此才能获得不希望的结果:

    <tr>
    <td id="idtypesectype2">Skype</td>
    <td id="doubledotsec">:</td>
    <td>
        <?php
        $search = $_GET['search']; 
        $sql ="SELECT * FROM contact_info WHERE CU_id='$search' AND contact_information_type='social_media_skype' AND visibility='1'";
        $result = $db -> query($sql);
        if($result->num_rows < 0) { 
            echo "-"; 
        } else { 
            WHILE ($row=$result->fetch_assoc()) {
                echo $row['contact_information']; 
            } 
        ?><br>
        <?php 
        } 
        ?>
        </td>
    </tr>
    

    【讨论】:

    • 谢谢,我会努力的。
    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多