如何使用PHP / MySQL从表中提取数据

时间:2015-02-02 17:20:30

标签: php mysql html-table

我知道这个问题已被多次询问,但仔细查看并尝试解决方案并没有让我走得太远。

我希望该表的格式为:

First name | Last Name
Mike         Hannover
Steve        Dortmund

但是我不知道如何实现这一目标,它目前的表现就像我已经尝试过的表格一样。

FirstName: Mike - LastName: Hannover
FirstName: Steven - LastName: Dortmund

我已在下面附上我的PHP代码,并提前感谢您的时间和帮助。

<body>
<h1>Clients information</h1>

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "lastgo";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT FirstName, LastName FROM info";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "FirstName: " . $row["FirstName"]. " 
- LastName: " . $row["LastName"].  "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

3 个答案:

答案 0 :(得分:1)

构建表格的更简单方法可能是将其作为表格进行。

// Just looking at this part of the code.
if ($result->num_rows > 0) {
  // Begin a table
  echo "<table>";
  // Create a header row
  echo "<tr><th>First Name</th><th>Last Name</th></tr>";
  while($row = $result->fetch_assoc()) {
     // output data for each row
     echo "<tr><td>" . $row["FirstName"]. "</td><td>" .       
    $row["LastName"]. "</td></tr>";
  }
  // Close table
  echo "</table>";
} 

答案 1 :(得分:0)

据我所知,您希望像这样打印您的FirstnName和LastName

将您的while循环更改为:

 echo "<table>";
 echo "<th>FirstName: </th><th>LastName</th>";   
 while($row = $result->fetch_assoc()) {

     echo "<tr>".
              "<td>" .$row["FirstName"] ."</td>"
             ."<td>" . $row["LastName"]."</td>
           .</tr>>";
    }
echo "</table>";

答案 2 :(得分:0)

您可以使用表格,然后按照您希望记录显示的方式设置样式

<table>
<tr>
    <td>Name</td>
    <td>Last Name</td>
</tr>
<?php foreach ($names as $value) : ?>
    <tr><td><?php echo $value['Name']; ?></td><td><?php echo $value['LastName']; ?></td></tr>
<?php endforeach; ?>
</table>

enter image description here