Is prepare needed for insert query? (7 posts)

  1. Gregg Banse
    Posted 1 year ago #

    I've been reading about protection from SQL injection attacks which I want to do but I can't tell if I'm supposed to use prepare on a SQL insert or not.

    Reading Andrew Nacin's post about the change to prepare it looks like it's only on reads from the database. But the example in the Codex shows an Insert. The example also uses a Post ID which I wouldn't have with pushing new data into a database.

    So I think the answer is no but I'd really like to know for sure.


  2. Jason
    Posted 1 year ago #

    Hi Lorax!

    There's never a circumstance in which it's a bad idea to use Prepare. Use it when you Insert, Select, Update, and Delete. You want to be protected in all circumstances from SQL injection, not just some.

    I've also found that using prepared statements helps organize your code better and force you to be more intentional on when and how you're interacting with the database -- as opposed to executing SQL here and there whenever it seems convenient.

    Hope this helps!

  3. Gregg Banse
    Posted 1 year ago #

    Thanks Jason,
    I agree and would prefer to use it but I'm having a bit of trouble with

    <li>syntax on a Select *</li>
    <li>how to check to see if it's working</li>

    [Moderator Note: Please post code & markup between backticks or use the code button. Your posted code may now have been permanently damaged by the forum's parser.]

  4. Gregg Banse
    Posted 1 year ago #


  5. Andrew Nacin
    Lead Developer
    Posted 1 year ago #

    If you're using $wpdb->query( "INSERT INTO ..." ) then you need to prepare things. But nearly all insertions can simply be done by $wpdb->insert(), which does not require a prepare as that is done internally.

  6. Gregg Banse
    Posted 1 year ago #

    Perfect. Thanks Andrew. Would the same be true of $wpdb->update -- that's taken care of internally?

  7. Gregg Banse
    Posted 1 year ago #

    For anyone that reads this thread these were helpful:

    Data Validation (codex)
    Data Sanitation and Validation (external)

Topic Closed

This topic has been closed to new replies.

About this Topic