简体   繁体   中英

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 ...

    $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. So for one hundred users there is 101 queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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