样式化来自PHP循环的数据库输出

我试图显示数据库中的数据,对我来说很重要的一点是,此输出位于网站的不同侧。我使用php连接到数据库,并使用ajax jquery刷新数据,因为每20秒的值都会更改。

I tried to echo <div styles='position: absolute; top: 0px' class='text'>{$row['id']}</div> in a foreach loop but when I do this all 6 of my id's are stacked on top each other. Making <div> outside loop was unsuccessful too. I guess my problem is in reading data from database because I read all at once but I don't know any other way to do this except wrtiting 6 connection files to gather only the one value that I want to display and then styling it, but I feel like there is smarter way of doing this.

这是我的代码。只是想说这是我第一次接触php。

<?php
$hostname = "someinfo";
$username = "someinfo";
$password = "someinfo";
$db = "someinfo";
$dbconnect = mysqli_connect($hostname,$username, $password,$db) or die("cant");
if ($dbconnect->connect_error) {
      die("Database connection failed: " . $dbconnect->connect_error);
}
$sensor_names = array();
$query2 = mysqli_query($dbconnect,"show tables");
while($row2 = mysqli_fetch_array($query2)){ 
    if($row2[0] == 'sensors' or $row2[0] == 'measurments'){
            break;
    }
    else{
            array_push($sensor_names,$row2[0]);
    }
}

$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, max(dev.id), dev.temprature, dev.date  from sensors s, `{$sensor_names[0]}` dev where s.id=dev.sensor_id gro
up by s.id, s.sensor_name order by s.id asc");
while($row = mysqli_fetch_array($query)){ //i konw this is ugly but this is working placeholder
foreach($sensor_names as $sn){

    $query = mysqli_query($dbconnect, "select s.id, s.sensor_name, dev.temprature, dev.date from sensors s, `{$sn}` dev where s.id=dev.sensor_id order by dev.id desc limit 1");
    $row = mysqli_fetch_array($query);
    echo "
    {$row['id']}
    {$row['sensor_name']}
    {$row['temprature']}
    {$row['date']}
    <br>";

}
}
?>
评论
  • hunks
    hunks 回复

    这是一个很久没接触过PHP的人的即兴消息,因此请注意主要的错误。但是基本思想是这样的:在变量中构建代码,完成后回显整个变量。使添加所需的结构/格式更加容易。请注意,您还可以将样式标记与该代码一起粘贴,并将样式与“表格”一起模糊化(个人而言,我不会使用表格进行样式设置,这只是用于演示)。

    $out = '<style>.cell_id{font-weight:bold;}</style>';
    $out .= '<table><tr><th>Label 1</th><th>Label 2</th><th>Etc</th></tr>'; //<=== ADDED!
    while($row = mysqli_fetch_array($query)){
       foreach($sensor_names as $sn){
         $query = mysqli_query($dbconnect, etc. etc. etc.);
         $row = mysqli_fetch_array($query);
         $out .= "
         <tr>
           <td class='cell_id'>{$row['id']}</td>
           <td>{$row['sensor_name']}</td>
           <td>{$row['temprature']}</td>
           <td>{$row['date']}</td>
         </tr>";
       }
    }
    echo $out;