PHP MySQL display data by id from database - freed

2019-08-28 02:57发布

I would like to have the freedom to place a row entry from my database wherever i' prefer in the page. Right now, the php code that I use is as follows (it is clean working code):

<html><head></head>
<body>
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);

$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);

echo $row['id']; while($row = mysql_fetch_array( $result )) {

echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
?>
</body>
</html>

I call id through the browser Eg. http://site.com/getid.php?id=10 . But I do not have the freedom to place my row entry within my html. For eg. like this:

<table><tr>
 <td align="center">BASIC INFO 1: <?php echo $row['basic1']; ?></td>
 <td align="center">BASIC INFO 2: <?php echo $row['basic2']; ?></td>
</tr></table>

I can place html within echo PHP tags but then I have to clean up my html and thats a lot of work. Retaining HTML formatting would be preferred. Any help or guidelines on this would be much appreciated.

标签: php html mysql
2条回答
手持菜刀,她持情操
2楼-- · 2019-08-28 03:37

Instead of having your HTML tags as part of the PHP variable, do something like this instead:

<table><?php foreach($row as $r):?>
    <td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>
查看更多
Juvenile、少年°
3楼-- · 2019-08-28 03:38
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);

$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);

//you need to retrieve every row and save to an array for later access
        for($rows = array(); $tmp = mysql_fetch_array($result);)
        {
            $rows[] = $tmp;
        }

//now you can use the $rows array where every you want e.g. with the code from Zhube
?>

....

<table><?php foreach($rows as $r):
    <td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>

By

while($row = mysql_fetch_array( $result )) {

echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}

you save only the last row

查看更多
登录 后发表回答