dongshuiga2826 2019-02-01 10:55
浏览 66
已采纳

虽然循环不会停止迭代数组

I have a php file in which I created a class Bank - has 2 methods - first one produces 5 users and populates random transactions in the database The second one should display the balance of the users.

I've searched on the site and no one had such an example on here.

I've successfully connected to database and wrote a (not a really good) query to fetch me all data from both tables.

$query = "SELECT * FROM users, transactions";

The problem I'm facing is that I'm not that good at php and the syntax is driving me crazy - my while loop loops through the result that the query produces but it does not stop after it goes through all the result rows in the array - it just repeats itself endlessly.

$connection = mysqli_connect('localhost', 'root', 'root', 'ipromapp', '3306');

class Bank
{
    function balance() 
    {
        global $connection;

        if($connection)
        {
            echo ("Connection online<br>");
        }

        $query = "SELECT * FROM users, transactions";

        $result = mysqli_query($connection, $query) or die(mysql_error());

        echo "<table border='1px'>";
        echo "<tr>";
        echo "<td> ID </td>";
        echo "<td> Name </td>";
        echo "<td> Balance </td>";
        echo "</tr>";

        while($row = mysqli_fetch_array($result))
        {
            $id = $row[0];
            $name = $row[1];
            $balance = $row[2];

            echo "<tr>";
            echo "<td> {$id} </td>";
            echo "<td> {$name} </td>";
            echo "<td> {$balance} </td>";
            echo "</tr>";
        }
        echo "</table>";
    }
}
$bank = new Bank;
$bank->randomize();
$bank->balance();

The results are as following ( there are 5 users in the database atm ) http://prntscr.com/mf6edg

It just goes and goes.

I'm 100% it is the while loop but I don't have the knowledge about how to change the condition inside it, if one would be kind enough to please help me out.

  • 写回答

1条回答 默认 最新

  • duandao8607 2019-02-01 10:59
    关注

    Your query will select all the rows of the second table for each row of the first table (your select produces a cartesian product).

    Assuming your tables are related by a key eg: user_id you should try a join

      SELECT * 
      FROM users u 
      INNER JOIN  transactions t  on u.user_id =  t.user_id 
    

    in this way you should obtain only transaction related to the specific user_id

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算