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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应