如何从数据库中回显具有特定ID的行

时间:2017-06-28 04:11:01

标签: php html mysql

首先,我的数据库表设置如下:

  

id | userid |金额|日期|状态

     

1 | 10 | 25.00 | 2017-09-12 |无

我希望将包含userid 10的所有行回显到html表中。我试过这个:

<?php
$id = $_GET['id'];
$userinfo= $mysqli->query("SELECT * FROM invoices WHERE userid = $id");
$row = mysql_fetch_array($userinfo) or die();

echo '<table>';
while($row = mysql_fetch_array($query)){
  echo '<tr>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['id'].'</td>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['amount'].'</td>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['date'].'</td>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['status'].'</td>
        </tr>';
}
echo '</table>';
?>

没有任何显示。

3 个答案:

答案 0 :(得分:1)

使用以下代码:

1。使用$ userinfo而不是$ query while($row = mysql_fetch_array($query))

2。将$mysqli->query更改为mysqli_query

3。使用mysqli代替mysql

<?php
$id = $_GET['id'];

//mysqli_connect("host","username","password","dbname") 
$conn=mysqli_connect("localhost","root","","dbname");
$sql="SELECT * FROM invoices WHERE userid = '.$id.'";
$result=mysqli_query($conn,$sql);

echo '<table>';
while($row = mysqli_fetch_array($result)){
  echo '<tr>
  <td>' .$row['id'].'</td>
  <td>' .$row['amount'].'</td>
  <td>' .$row['date'].'</td>
  <td>' .$row['status'].'</td>
        </tr>';
}
echo '</table>';
?>

答案 1 :(得分:0)

将mysqli与mysql和面向对象的样式混合使用Procedural

使用面向对象

<?php
$id = $_GET['id'];
$userinfo= $mysqli->query("SELECT * FROM invoices WHERE userid = $id");  
echo '<table>';

while($row = $userinfo->fetch_assoc()){
  echo '<tr>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['id'].'</td>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['amount'].'</td>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['date'].'</td>
  <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['status'].'</td>
        </tr>';
}
echo '</table>';
?>

答案 2 :(得分:0)

请改为尝试:

<?php
   $id = $_GET['id'];
   $mysqli = new \mysqli('localhost', 'username', 'password', 'database');
   $userinfo= $mysqli->query("SELECT id, amount, date, status FROM invoices WHERE userid = $id");

  echo '<table>';
  if ($userinfo->num_rows > 0) {
     while($row = $userinfo->fetch_assoc()) {
        echo '<tr>
           <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['id'].'</td>
           <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['amount'].'</td>
           <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['date'].'</td>
           <td><font size="2" face="Lucida Sans Unicode" color=#EBEBEB>' .$row['status'].'</td>
        </tr>';
     }
  }
  else {
     echo "0 rows returned";
  }
  echo '</table>';
?>

另外,我只是在讨厌但在你的选择陈述中不使用*。即使您想要每个字段,也要始终列出字段。您还应该使用准备好的陈述。