Jump to content

Archived

This topic is now archived and is closed to further replies.

bwaxse

sql query help

Recommended Posts

Alright so im pretty new to php and sql - I know theres an easier way to do this:

I have Class IDs set in the Users Table and I want to get the Class Names by referencing the Classes table.
The if statements - If a user has a class entered in, look up that ID and set the $_SESSION[CLASS#] equal to that name.

<?php
                        if ($_SESSION['CLASS1'] != "0"){
        $query2 = "SELECT sClassName FROM tbl_classes WHERE sClassID ='".$_SESSION['CLASS1']."'";
        $result2 = mysql_query($query2) or die("Invalid query: " . mysql_error());
        $row2 = mysql_fetch_assoc($result2);
       
        $_SESSION['CLASS1'] = $row2['sClassName'];}

        if ($_SESSION['CLASS2'] != "0"){
        $query3 = "SELECT sClassName FROM tbl_classes WHERE sClassID ='".$_SESSION['CLASS2']."'";
        $result3 = mysql_query($query3) or die("Invalid query: " . mysql_error());
        $row3 = mysql_fetch_assoc($result3);
       
        $_SESSION['CLASS2'] = $row3['sClassName'];}
X4 More times
?>

Share this post


Link to post
Share on other sites
An IN clause would be most appropriate:

[code] "SELECT sClassName FROM tbl_classes WHERE sClassID IN ('".$_SESSION['CLASS1']."','".$_SESSION['CLASS2']."','".$_SESSION['CLASS3']."') ";[/code]

Share this post


Link to post
Share on other sites
Thanks a bunch, I used:
$sql = "SELECT * FROM tbl_classes WHERE sClassID = '".$_SESSION['CLASS1']."'||'".$_SESSION['CLASS2']."'||'".$_SESSION['CLASS3']."'
||'".$_SESSION['CLASS4']."'||'".$_SESSION['CLASS5']."'||'".$_SESSION['CLASS6']."'";

Is there a major difference or is one better than the other?

Share this post


Link to post
Share on other sites
Yes there is... the one you have shouldn't work!  You have to reference the column name as well with ORs.  I prefer using IN clauses because they make the intent of the query much clearer, and they can be optimized by the parser.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.