0

我试图从 DIV 中的 mysql 表中回显该行但不起作用,如果我输入:

     echo $row['test'];

在里面while( $row = $result->fetch_assoc() ){ }它工作得很好,但我希望它显示在 DIV 标签内。我知道我错过了一些东西,但不知道它是什么。谢谢你的帮助。

                            <?php
            $mydb = new mysqli('localhost', 'root', '', 'test');
            $sql = "SELECT * FROM test  order by id limit 1 ";
            $result = $mydb->query($sql);
            if (!$result) {
                echo $mydb->error;
            }
            while( $row = $result->fetch_assoc() ){ 
            }
            $mydb->close ();

            ?>
            <html>
            <head>
            </head>
            <body>
            <div><? echo $row['test'];?>
            </div>                            
4

3 回答 3

1

你只需要移动你的 html 和 php 代码。$row存在于 while 循环内部,而您将其置于 while 循环之外。

<?php
        $mydb = new mysqli('localhost', 'root', '', 'test');
        $sql = "SELECT * FROM test  order by id limit 1 ";
        $result = $mydb->query($sql);
        if (!$result) {
            echo $mydb->error;
        }
        ?>
        <html>
            <head></head>
            <body>
            <?php while( $row = $result->fetch_assoc() ){ ?>
                <div><?php echo $row['test'];?></div>
            <?php 
            }
            $mydb->close ();
            ?>
            </body>
        </html>

这将为从数据库中检索到的每一行创建一个新的 div。

于 2013-08-06T20:09:51.767 回答
0

您在获取之前关闭连接

       $mydb->close ();

删除该行并将其放在代码的末尾。

并将您的 html 代码放入 while 循环中。

 <?php
     $mydb = new mysqli('localhost', 'root', '', 'test');
     $sql = "SELECT * FROM test  order by id limit 1 ";
     $result = $mydb->query($sql);
  if (!$result) {
  echo $mydb->error;
 }
 ?> 
 <html>
 <head>
 </head>
 <body>
 <div>
 <?php
 while( $row = $result->fetch_assoc() ){
 echo $row['test'];
 }
 $mydb->close ();
 ?>
 </div>
 </body>
 </html>
于 2013-08-06T20:09:14.830 回答
0

您只需要再次放入块的$row['test']内部while,然后移动您的 HTML。

<?php
$mydb = new mysqli('localhost', 'root', '', 'test');
$sql = "SELECT * FROM test  order by id limit 1 ";
$result = $mydb->query($sql);
if (!$result) {
    echo $mydb->error;
}
?>
<html>
<head>
</head>
<body>
<div>
<?php
while( $row = $result->fetch_assoc() ){
    echo $row['test'];
}
$mydb->close ();
?>
</div>
</body>
</html>
于 2013-08-06T20:10:12.693 回答