Find the answer to your Linux question:
Results 1 to 9 of 9
I'm pretty new at PHP and MySQL. But I'm writing a piece of PHP that must iterate through an array of items and count how many times these items are ...
  1. #1
    Linux Engineer Freston's Avatar
    Join Date
    Mar 2007
    Location
    The Netherlands
    Posts
    1,047

    PHP & MySQL - problem with quoting

    I'm pretty new at PHP and MySQL. But I'm writing a piece of PHP that must iterate through an array of items and count how many times these items are in a MySQL table.


    It goes a little bit like this:

    Code:
    $list = array( item1, item2, item3 );
    
    foreach ( $list as $current )
    {
       $query[foo] = "select * from database.table
                      where bar = $current";     //$current is the problem
       $row = mysql_query($query[foo]) or die ("0h no");
       $interesting = mysql_num_rows($row);
       print "$interesting";
    }

    This however does work:
    Code:
    $list = array( item1, item2, item3 );
    
    foreach ( $list as $current )
    {
       $query[foo] = "select * from database.table
                      where bar = 'item1' ";     //$current is the problem
       $row = mysql_query($query[foo]) or die ("0h no");
       $interesting = mysql_num_rows($row);
       print "$interesting";
    }
    The problem is with the quotes. While selecting, I need to quote the value as 'value'... but when it's a $variable, the quotes prevent the expanding of the '$variable'. I tried escaping them, but that doesn't seem to work either. And using double quotes for "$variable" only makes it worst. Is there a trick to this?


    The reason I do this, is because I don't know in advance how many items end up in the $list array. It is itself a product of another MySQL query.
    Last edited by Freston; 07-05-2010 at 03:33 PM.
    Can't tell an OS by it's GUI

  2. #2
    Trusted Penguin elija's Avatar
    Join Date
    Jul 2004
    Location
    Either at home or at work or down the pub
    Posts
    2,300
    When I set up a little test and output your SQL from the first example I get

    Code:
    select * from database.table where bar = item1
    select * from database.table where bar = item2
    select * from database.table where bar = item3
    Assuming that item1, item2 and item3 are values of bar and not fields, they should be in single quotes as they are strings. Try this instead:

    Code:
     $query[foo] = "select * from database.table
                      where bar = '$current'";
    Or indeed this, which is actually better practice as it delimits the variable.

    Code:
     $query[foo] = "select * from database.table
                      where bar ='{$current}'";
    You should be able to get the same results with one database query. Consider:

    Code:
    SELECT bar, COUNT(*) AS howMany FROM Foo WHERE bar IN('item1', 'item2', 'item3') GROUP BY bar
    Hope this helps
    Last edited by elija; 07-05-2010 at 04:02 PM.
    If we hit that bullseye, the rest of the dominoes will fall like a house of cards. Checkmate! (Zapp Brannigan)


    My new blog. It's probably not as good as I think it is.

  3. #3
    Trusted Penguin elija's Avatar
    Join Date
    Jul 2004
    Location
    Either at home or at work or down the pub
    Posts
    2,300
    In fact

    Code:
    $query = "SELECT bar, COUNT(*) AS howMany FROM Foo WHERE bar IN(";
    foreach ($list as $current) {
    	$query .= "'{$current}', ";
    }
    $query = trim($query, ', ');
    $query .= ") GROUP BY bar";
    If we hit that bullseye, the rest of the dominoes will fall like a house of cards. Checkmate! (Zapp Brannigan)


    My new blog. It's probably not as good as I think it is.

  4. #4
    Linux Engineer Freston's Avatar
    Join Date
    Mar 2007
    Location
    The Netherlands
    Posts
    1,047
    Thanks elija!

    This was the trick:
    Code:
    $current = trim($current};
    $query[foo] = "select * from database.table
                      where bar = '{$current}';
    The problem was with the quoting, but also some unwanted whitespace was in the values of my array. That's two ' problems' for the price of one
    Can't tell an OS by it's GUI

  5. #5
    Linux Enthusiast Kloschüssel's Avatar
    Join Date
    Oct 2005
    Location
    Italy
    Posts
    717


    (banging head)

    sorry, if I am going to be rude. don't take it personally.

    PLEASE don't post stupid things that make things only worse. this solution actually compromises the server security because one can sql inject your query. it shows once again that most people do things without the slightest idea or interest of the matter. i dislike saying that, but YOU are one source why most web pages are seriously vulnerable because of server misconfiguration, bad programming and lack of other countermeasures. please, LEARN more of software engineering, one might misunderstand YOU being a software engineer without the actual engineering thing and others that are software engineers that comply to the engineering part, but are regarded as retards because of people working like you do.

    now back to topic. if you don't know how to SAFELY quote your arguments yet, I strongly recommend:

    1] understand/learn what I am talking about
    2] use the routines offered by mysql. if you don't know that they exist, look it up. you should already know the right resources where to find this kind information (likewise a documentation/manual - in this case the mysql one)
    3] start thinking when you are doing things

    Last edited by Kloschüssel; 07-06-2010 at 06:46 AM.

  6. #6
    Trusted Penguin elija's Avatar
    Join Date
    Jul 2004
    Location
    Either at home or at work or down the pub
    Posts
    2,300
    Quote Originally Posted by Kloschüssel View Post


    (banging head)

    sorry, if I am going to be rude. don't take it personally.

    PLEASE don't post stupid things that make things only worse. this solution actually compromises the server security because one can sql inject your query. it shows once again that most people do things without the slightest idea or interest of the matter. i dislike saying that, but YOU are one source why most web pages are seriously vulnerable because of server misconfiguration, bad programming and lack of other countermeasures. please, LEARN more of software engineering, one might misunderstand YOU being a software engineer without the actual engineering thing and others that are software engineers that comply to the engineering part, but are regarded as retards because of people working like you do.

    now back to topic. if you don't know how to SAFELY quote your arguments yet, I strongly recommend:

    1] understand/learn what I am talking about
    2] use the routines offered by mysql. if you don't know that they exist, look it up. you should already know the right resources where to find this kind information (likewise a documentation/manual - in this case the mysql one)
    3] start thinking when you are doing things

    Wow. I really wish I had your brain power and especially your psychic ability. It's a really cool super power being able to tell everything about code you haven't seen from an example snippet. It would make my day job so much easier if I could do that.

    Of course if data is coming from an untrusted source it should be escaped, used in prepared statements or if you are using MySQL 5, preferably moved into stored procedures.

    Benefit me with your wisdom O psychic one, if a hard coded array isn't a trusted source, what is?

    Freston, I will add here that data from a database, even your own database, especially one where more than one coder has worked on it and especially one that has data in it is not a trusted source.
    Last edited by elija; 07-06-2010 at 07:58 AM.
    If we hit that bullseye, the rest of the dominoes will fall like a house of cards. Checkmate! (Zapp Brannigan)


    My new blog. It's probably not as good as I think it is.

  7. #7
    Linux Engineer Freston's Avatar
    Join Date
    Mar 2007
    Location
    The Netherlands
    Posts
    1,047
    @Kloschüssel
    Hold your horses mate - false alarm

    I agree with every point you make, it's completely valid. But this is on my private lappy, and at no point in the code does it ask for user input. I have no pretence this part of the code will ever be internetfähig.


    Quote Originally Posted by Kloschüssel
    bad programming
    Code:
    $statement  = true;
    Don't let my 'Linux engineer' title here on LFo fool you, I'm by no means a good programmer. But I am practicing getting data from a database using PHP, yes.

    Quote Originally Posted by elija
    Freston, I will add here that data from a database, even your own database, especially one where more than one coder has worked on it and especially one that has data in it is not a trusted source.
    Most things I write are just finger practice. It'll be a while before I can do something productive. I'm sure to stop and have a look at the security secion of my books before then. I promice

    ___
    Posted without the benefit of a spell chekcer
    Can't tell an OS by it's GUI

  8. #8
    Linux Guru Lakshmipathi's Avatar
    Join Date
    Sep 2006
    Location
    3rd rock from sun - Often seen near moon
    Posts
    1,568

    Exclamation

    Quote Originally Posted by Freston View Post
    writing a piece of PHP that must iterate through an array of items and count how many times these items are in a MySQL table.
    Originally Posted by Kloschüssel
    this solution actually compromises the server security because one can sql inject your query.
    Unless he is taking input from users there is no need to worry about SQL injection.
    SQL injection - Wikipedia, the free encyclopedia
    - Lakshmipathi.G
    -------------------
    FOSS India Award winning ext3fs Undelete tool and tutorials www.giis.co.in
    First they criticize you,Then they laugh at you,Then they fight with you,Then you win. - M.K.Gandhi
    -------------------

  9. #9
    Linux Enthusiast Kloschüssel's Avatar
    Join Date
    Oct 2005
    Location
    Italy
    Posts
    717
    Unsafe code is always unsafe code, whether it will be executed by attackers or not. In the end you quite fast loose the overview and may get in the situation where previously "safe code because of a static array as parameter" becomes a argument from the outside world, wrapped through N function calls or you copy it into a productive environment because you have written it once and it worked pretty well back then. Oh, and there may be also that others search up exactly this problem, copy&paste the "working" code and open new security holes.

    Good that it is practice you are writing this little thingy for and if you ask me, even better that you just learned a important lesson. NEVER write unsafe code just 'cause it seems to be less work. Less work = code that mustn't be maintained.

    I didn't want to step on any toes or feets, I just can't say it loud enough: don't give out toxics as long one thinks it is a cookie.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...