从数据库中提取数据。如何编写 PHP MYSQL 循环函数

问题如下。我有两个表用户和卡。当用户有两张或更多卡时,如何编写循环函数?示例:用户 bane 有卡片 222222 和 454545。但是,当我向搜索字段发送问题时,它只抛出第一张卡片。


<?php 

    require "connection.php";

    $search = $_POST['search'];


    $sql = "SELECT users.first_name, users.second_name, cards.card_number

            FROM users

            INNER JOIN cards

            ON cards.user_id = users.id

            WHERE cards.card_number = '$search'

            OR users.first_name = '$search'

            OR users.second_name = '$search'";


    $query = mysqli_query($db, $sql);

    $result = mysqli_fetch_assoc($query);


    echo $result['first_name']." ".$result['second_name']." ",

    $result['card_number']; ?>

https://i.stack.imgur.com/0VvXF.jpg


开满天机
浏览 101回答 2
2回答

繁花不似锦

您正在返回一个值。如果我必须出示所有用户卡,我会这样做。<?php     require "connection.php";    $search = $_POST['search'];    $sql = "SELECT users.first_name, users.second_name, cards.card_number            FROM users            INNER JOIN cards            ON cards.user_id = users.id            WHERE            users.first_name = '$search'            OR users.second_name = '$search'";    $query = mysqli_query($db, $sql);while ($row = mysqli_fetch_assoc($query)) {    echo $row['first_name']." ".$row['second_name']." ",    $row['card_number']; } ?>这应该为每张卡打印一行。您还可以更改类似这样的 where 子句来查找部分字符串:users.first_name LIKE '%$search%' 但是,如果您希望能够搜索卡号并找到其所有者的所有关联卡,那么您必须采取一些额外的步骤。我会去做这样的事情: SELECT t1.customerIDi, cards.number, customer.*  FROM CARDS LEFT JOIN customer ON cards.CustomerID = customer.id INNER JOIN (     SELECT customer.id AS customerIDi     FROM customer     LEFT JOIN cards     ON cards.CustomerID = customer.id     WHERE     Cards.Number = "$search" ) AS t1 ON t1.customerIDi = cards.CustomerID我嵌套了一个选择来查找卡所有者,然后获取所有关联的卡。

HUWWW

跑步$results = mysqli_fetch_assoc($query);foreach( $results as $result) {&nbsp; &nbsp; echo .....}
打开App,查看更多内容
随时随地看视频慕课网APP