简体   繁体   English

如何从数据库中获取所有用户数据?

[英]how to fetch all user data from database?

i want fetch all users data but am getting only one user details, please help me to solve 我想获取所有用户数据,但只获取一个用户详细信息,请帮助我解决

$conn = mysqli_connect("localhost", "root", "", "bitmining");
$sql6="SELECT username FROM users";         
if($result = mysqli_query($conn, $sql6)){       
    while ($row=mysqli_fetch_array($result)){               
    //Hashrate Data Fetch
    $investedusername = $row['username'];

    $sql3="SELECT sum(hashrate_amount) as total FROM buyhashrate WHERE invested_username='$investedusername'";
    $result = mysqli_query($conn, $sql3);           
    $row = mysqli_fetch_assoc($result);
    //Total Value of Hashrate
    echo $row['total'] . " GH/s";               
    echo "<br />";      
}
    $result->close();
}

Your re-using the $result field, change your second reference to something like ... 您重新使用$ result字段,将第二个引用更改为类似...

    $result1 = mysqli_query($conn, $sql3);           
    $row = mysqli_fetch_assoc($result1);

This will stop it reseting the value your using for your main loop in 这将阻止它重置您在主循环中使用的值

while ($row=mysqli_fetch_array($result)){ 

您将$ result变量用于mysqli_query $ result = mysqli_query($ conn,$ sql3);

While other answers are right about your mistake, I want to give you a better solution. 尽管其他答案对于您的错误是正确的,但我想为您提供更好的解决方案。

Try to use a join like this: 尝试使用这样的联接:

$conn = mysqli_connect("localhost", "root", "", "bitmining");
$sql="SELECT SUM(hashrate_amount) AS total FROM users AS t1 LEFT JOIN buyhashrate AS t2 ON (t1.username=t2.invested_username) GROUP BY t1.username";         
if($result = mysqli_query($conn, $sql)){       
    while ($row=mysqli_fetch_array($result)){               
        //Total Value of Hashrate
        echo $row['total'] . " GH/s";               
        echo "<br />";      
    }
    $result->close();
}

This way you do just one query from database. 这样,您只从数据库中执行一个查询。 But using your method you have n+1 queries which n is the number of users. 但是使用您的方法,您有n + 1个查询,其中n是用户数。 So for one hundred users there is 101 queries. 因此,对于一百个用户,有101个查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM