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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀