简体   繁体   中英

Is it bad to put a Query inside an while loop?

I built a Query inside an While loop to get the status from my users. Is there any problem by doing that?

I would like to do it in a different way.

My code.

 $output = array();

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

        if ($row['user_id'] !=  $id)
        {

            $checkstatus= mysqli_query($con,"SELECT session_id, status FROM frei_session WHERE session_id = '".$row['user_id']."' ");
            $status = mysqli_fetch_row($checkstatus);

            if(!$status[0]){
            $row['status'] = 0;
            }

            $output[] = $row;
        }

    }
    $json = json_encode(array("contacts" => $output ));
    print($json);

Thank you.

It will blow up your code and can result in very bad performance, escpecially when your main query is returning a lot of rows. A SQL-Server can connect different tables much more efficient by using Joins . For me it seems like a good scenario to use them here. Especially the LEFT-JOIN can be usefull to load a session. It will return NULL for the requested fields when there is no session connected with the current user.

But because I don't even know your main query or much less the use behind your code, you've to decide whether a user without a session makes sense in your case. If not, use a EQUAL-JOIN instead. Then your query wouldn't return any data if no session exists.

An example how can such a JOIN can look when you've two tables USER and SESSION:

SELECT user.username, user.email, 
       session.status AS session_status
FROM user, session
WHERE user.userid = 123
AND session.session_id = user.user_id

I don't see any problem with having a query like yours inside the while loop. It would become problematic if the query was inefficient (imagine if the query would return 10 lines and you would only use/need 1), but you are targeting your user in the where clause, so it's OK.

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