Skip to content
Advertisement

get the index number of data gotten from mysql database

I am trying to get all user data from my mysql table and i want to check the index number of where a particular data is for example if there are 10 users in the database and after getting the data from it i want to check if any of the user ID matches the one i have then get the index number where he is placed at. if his data is in number 4 or 8

    $userId= '****';
    $active = 'active';
    $sql = $conn->prepare("SELECT * FROM users WHERE status=? ORDER BY date DESC, class DESC");
    $sql->bind_param("s", $active);
    $sql->execute();
    $res = $sql->get_result();
    if (mysqli_num_rows($res) > 0) {
        while ($row = $res -> fetch_assoc()) {
            if($userId == $row['userId']) {

               ///Get the number he is in the array of 10 users...

            }
        }
    }
    else {
        echo json_encode("no_user");
    }

Advertisement

Answer

Increment a counter variable in the loop.

        $index = 0;
        while ($row = $res -> fetch_assoc()) {
            if($userId == $row['userId']) {
               echo $index;
            }
            $index++;
        }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement