Reputation: 657
I was trying to echo the row from mysql table inside a DIV but doesn't work, if I put:
echo $row['test'];
inside while( $row = $result->fetch_assoc() ){
}
it works perfect but I wanted it to show inside a DIV tag. I know I am missing something but don't what it is. Thanks for your help.
<?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>
Upvotes: 0
Views: 294
Reputation: 7566
You just need to move your html and php code around. $row
exists inside of the while loop and you have it outside the while loop.
<?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>
This will create a new div for each row retrieved from the database.
Upvotes: 1
Reputation:
You simply need to put the $row['test']
inside of your while
block again, and move your HTML around.
<?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>
Upvotes: 0
Reputation: 37243
you are closing connection before fetching
$mydb->close ();
remove that line and put it in the end of your code.
and put your html code inside the while loop.
<?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>
Upvotes: 0