如何从sql数据库中回显所有数据? [关闭]

问题描述 投票:-2回答:2

我正在尝试回应最近的交易。它存储在数据库中。该数据库如下所示:

ACTION | CARD | AMOUNT | TIME
ADD    | 123  | 10.00  | 14:37 
REMOVE | 123  | 5.00   | 12:20
ADD    | 123  | 2.50   | 11:18

我使用了以下php代码:

$sql = "SELECT * FROM transactions ORDER BY time DESC LIMIT 5";
if($result = mysqli_query($con, $sql)){
     if(mysqli_num_rows($result) > 0){

        while($row = mysqli_fetch_assoc($result)){
            echo $row['action'];
            echo $row['amount'];
            echo $row['card'];
            echo $row['time'];

        }
    }
}

仅显示以下内容:add10.0012314:37因此仅第一行。如何实现对数据库中的每一行都完成的操作?

php html mysql
2个回答
-2
投票

如果要获取最近的交易,请使用:

SELECT * FROM transactions ORDER BY time DESC

-2
投票

简单易用的SQL注入避免使用准备好的语句并使用最新的代码,

这里是php.net的准备好的语句示例

通过在此处限制查询LIMIT 5";,您仅显示db的5个结果。

如果要在数据库表中显示所有数据,则应像这样查询,没有必要的子句和限制:descasc达到所需。

if ($stmt = $con->prepare("SELECT * FROM transactions ORDER BY time DESC")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    $stmt->close();
}
/* close connection */
$con->close();

如果要使用where子句显示db表中的所有数据,请尝试:

$email = "[email protected]";
$stmt = $con->prepare("SELECT * FROM transactions  WHERE email=? ORDER BY time DESC");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();    
$stmt->bind_result($id, $name);  // <- Add; #args = #cols in SELECT
if($stmt->num_rows == 1) {
    while ($stmt->fetch()) {
        echo $id, $name;  // <-- then you can do this.
    }
}

如果使用我的示例后仅得到1行,则表示您有数据库中只有1行

© www.soinside.com 2019 - 2024. All rights reserved.