简体   繁体   中英

Gobbly php to usable SQL?

So I need help converting PHP to SQL. This is the current code (not mine) and it runs three while loops that end up taking about two and a half minutes to run. Obviously, not very efficient. I also know that it's the old mysql usage and not the newer mysqli or PDO version..

Here's a fiddle for the sample data:

http://sqlfiddle.com/#!2/71c74

Looking at the php, I think that this is the query (using SQL).

SELECT z.siteID, us.id FROM groups g, usertogroup u, users z, usertosite us 
WHERE g.entityID=$thisEntity
and u.groupID=2093 and z.id=userID
and site_id=3411  and user_id=$uid;

(Replaced with real values).

But that returns 1000+ rows when the query should only return 44. So here's the PHP, anyone know what the real query should look like, or maybe a nicer way to write this in PHP? The $uid is pulled from the superglobal $_SESSION variable, so it's been set. Same with $thisEntity, also pulled from a session variable.

$site_list3 = array();
$sql_str = "SELECT id FROM groups WHERE entityID=$thisEntity";

$sql_res = mysql_query($sql_str);

$row = mysql_fetch_array($sql_res, MYSQL_ASSOC);


while ($row) {
    $passed = 1;

    $sql_str2 = "SELECT siteID FROM usertogroup u,users z where groupID=" . $row['id'] . " and z.id=userID;"; 

    $sql_res2 = mysql_query($sql_str2);

    $row2 = mysql_fetch_array($sql_res2, MYSQL_ASSOC);    

    while ($row2) {

        if ($thisEntity == 1761 && $row2['siteID'] == 3411) {

        } else {
            $sql_str3 = "SELECT id FROM usertosite WHERE site_id=" . $row2['siteID'] . " and user_id=$uid";

            $sql_res3 = mysql_query($sql_str3);

            $row3 = mysql_fetch_array($sql_res3, MYSQL_ASSOC);

            if (!$row3)
                $passed = 0;
        }

        $row2 = mysql_fetch_array($sql_res2, MYSQL_ASSOC);
    }

    if ($passed == 1)
    {
        $site_list3[] = (int) $row['id'];

    }



    $row = mysql_fetch_array($sql_res);




}
$site_list3_values = implode(", ", $site_list3);

It looks like you're missing one or more JOIN clauses. Without a working schema, I can only guess... But does this work?

SELECT
  U.siteID,
  US.id
FROM
  groups G
  JOIN usertogroup UG ON(UG.groupID=G.id) -- was missing?
  JOIN users U ON(U.id=U.userID)
  JOIN usertosite US ON(US.user_id=U.id) -- was missing?
WHERE
  G.entityID = 12345
  AND US.site_id = ABCDEF
  AND ....

Where possible, I personally prefer "ON" conditions to "WHERE" expressions, because I think it makes the relationships between tables more evident.

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