Discussion: Select Single Column Using MySQL

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • charles07
    New Member
    • Dec 2011
    • 45

    Discussion: Select Single Column Using MySQL

    have you ever wondered how to select a single coloumn from mysql using php, then checking whether a value or variable exist in the resulting array... well here is the code

    Code:
    $busid = '5412';
    $results    =   mysql_query("SELECT `myname` FROM mytable WHERE myuser = 'user'");
            while($rows = mysql_fetch_array($results))
            {   
                $colnames[] = $rows['myname'];
            }
            if(!in_array($busid, $colnames))die("Access denied");
    Last edited by Dormilich; Dec 15 '11, 10:39 AM. Reason: please use [CODE] [/CODE] tags when posting code
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    why going to the extend of using arrays? just get the count: SELECT COUNT() FROM mytable WHERE myuser = ? AND `myname` = ?

    Comment

    • NeoPa
      Recognized Expert Moderator MVP
      • Oct 2006
      • 32663

      #3
      This wasn't close to Article quality, but may prove useful as the seed for a discussion.

      Comment

      • charles07
        New Member
        • Dec 2011
        • 45

        #4
        thanks Dormilich,

        i think you are right. let me try out your code & would get back to you.

        Comment

        • charles07
          New Member
          • Dec 2011
          • 45

          #5
          thanks Dormilich

          i used the below query, now it works fine,

          SELECT `myname` FROM mytable WHERE myuser = 'user' and myname='5412'

          Is there any difference between the above query & your query(SELECT COUNT() FROM mytable WHERE myuser = ? AND `myname` = ?), which is better?

          iam a enthusiastic newbie to PHP, googled the same topic but couldn't get an answer, now it looks fine

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            Is there any difference between the above query & your query
            there is. my query will always return one result (the number of rows) while your query returns all matching rows, which a) can be no results at all and b) returns redundant information (the myname field)

            Comment

            • charles07
              New Member
              • Dec 2011
              • 45

              #7
              but how do i check whether the result is above 0

              Comment

              • Dormilich
                Recognized Expert Expert
                • Aug 2008
                • 8694

                #8
                it is the result* of my query. you can directly use it in a comparison.

                e.g. by using PDOStatement->fetchColumn( )

                Comment

                Working...