PDO DB查询到HTML

时间:2019-03-01 15:33:55

标签: php html pdo

我试图在同一页面上回显3个不同的查询,但是我似乎失败了,不得不向数据库询问3次才能回显的答案,我认为这看起来很差并且可以简化,但这非常对我来说是新的。

当前我有3个Bootstrap卡,它们显示不同的信息(全部来自同一张表)。

可以使用PDO完成吗?整齐了吗?

<div class="card-deck">
  <div class="card">
    <div class="card-header"><i class="fa fa-desktop"></i> Total Assets</div>
    <div class="card-body">
      <h5>

<?php
// Include config file
require_once "includes/config.php";

// Prepare the select statement
$sql="SELECT * FROM asset_details";
if ($result=mysqli_query($con,$sql)) {
    // Return the number of rows in result set
    $rowcount=mysqli_num_rows($result);
    printf("Total Number of Assets %d \n",$rowcount);
    // Free result set
    mysqli_free_result($result);
}
mysqli_close($con);
?>
</h5>
    <a href="#" class="btn btn-primary">Record Asset</a>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
  <div class="card">
      <div class="card-header"><i class="fa fa-mobile"></i> Total Phones</div>
    <div class="card-body">
            <h5>
<?php
$con=mysqli_connect("localhost","root","","asset_db");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM asset_details WHERE type = 2";

if ($result=mysqli_query($con,$sql)) {
    // Return the number of rows in result set
    $rowcount=mysqli_num_rows($result);
    printf("Total Number of phones %d \n",$rowcount);
    // Free result set
    mysqli_free_result($result);
}
mysqli_close($con);
?>
</h5>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
  <div class="card">
    <div class="card-header"><i class="fa fa-laptop"></i> Total Laptops</div>
    <div class="card-body">
            <h5>
<?php
$con=mysqli_connect("localhost","root","","asset_db");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM asset_details WHERE type = 1";

if ($result=mysqli_query($con,$sql)) {
    // Return the number of rows in result set
    $rowcount=mysqli_num_rows($result);
    printf("Total Number of Laptops %d \n",$rowcount);
    // Free result set
    mysqli_free_result($result);
}

mysqli_close($con);
?>
</h5>

    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
</div>

我不认为我需要调用该查询3次(尽管它们都不同)。第一个给出总数,第二个给出基于类型整数2的数字,第三个给出类型整数为1的类型。type是表中的字段。

任何人都可以为我指出正确的方向以进行整理(理想情况下,通过在此处和config.php中使用PDO使我与2019保持同步)?

0 个答案:

没有答案