in reply to Re: foreach within a foreach
in thread foreach within a foreach

Just out of curiousity, and not in argument, because I do not know the answer to the question.

But why, particularly, are placeholders better than using your own variable?

Replies are listed 'Best First'.
Re^3: foreach within a foreach
by tadman (Prior) on Jun 07, 2002 at 20:02 UTC
    Placeholders make sure that the data is quoted correctly. Remember, when inserting strings into your database, they must be surrounded by quotes, yet numbers cannot be. This strict either/or but not both situation means that you need to decide in advance how to quote. If you put quotes in your statement, but change data types later, you are going to break that part of your program in some way that isn't visible until that statement is run.

    The other thing you can do is let DBI do it for you, which is what placeholders do. DBI keeps track of how each column has to be treated, and quotes accordingly. As an additional bonus, some driver implementations, such as DBD::mysql can actually save these generic statements and recycle them later. In shotgunefx's example, the execute could be called many times on exactly the same prepared statement.
      Changing my scripts now. <grin>

      Thanks for the complete answers everyone, and the link- you helped me learn quite a bit, and save a bit of time, too.
      ++ to all. :)
Re: Re: Re: foreach within a foreach
by dsheroh (Monsignor) on Jun 07, 2002 at 20:06 UTC
    Efficiency. If you use placeholders, you only need to prepare() the statement once (at which point the db engine analyzes it and figures out how to most efficiently process the query) and can then execute it repeatedly, passing in different parameters each time. Without placeholders, the query has to be re-prepared each time it is executed.
Re: Re: Re: foreach within a foreach
by shotgunefx (Parson) on Jun 07, 2002 at 20:04 UTC
    Well depending on what's in your $vars, it could break your SQL if it contains ? or a quote. more on this

    The other reason is that you don't have to keep preparing a statement over and over. The poster could move the prepare outside of both foreach loops and only prepare it once. Over thousands of iterations, this can make a noticable difference.

    -Lee

    "To be civilized is to deny one's nature."