dongyi2534 2018-05-14 12:20
浏览 42
已采纳

value字段没有接收php变量

<?php
        $servername = "localhost";
        $username = "root";
        $password = '';
        $dbname = "db_code";
        $conn = new mysqli($servername, $username, $password, $dbname);
        $sql = "SELECT Otp FROM otptable";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "Otp: " . $row["Otp"] ."<br>";
                x = " . $row["Otp"] .";
            }
        }
        ?>
        <body>
         <div id="floating-panel">
              <input id="latlng" type="text" value="<?php echo $row["otp"]?>">
        </body>

data is not coming in value field but working in above echo. How to insert in value??
Can i store that $row["otp"] in a variable and then echo it in value tag. if yes then how?

  • 写回答

1条回答 默认 最新

  • dongtangxi1584 2018-05-14 12:25
    关注

    Because you're trying to use it outside the loop, so $row doesn't contain anything meanignful by that point. (By definition $row has to be false by then or the loop would never have ended.)

    You could store the value in a variable to use after the loop, for example:

    $otp = "";
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $otp = $row["Otp"];
        }
    }
    <input id="latlng" type="text" value="<?php echo $otp; ?>">
    

    Of course, be aware that this will always display the last value from the loop. (The loop itself is kind of unnecessary at that point, you could just narrow the query to return only that one last row that you want.) Again, this is because this is happening outside the loop and therefore only happens once, after the loop.

    Conversely, if you want to display multiple values in multiple elements on the page, you'd more likely want to put those elements in the loop. For example:

    while($row = $result->fetch_assoc()) {
    ?>
        <input id="latlng" type="text" value="<?php echo $row["Otp"]; ?>">
    <?php
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?