WordPress.org

Ready to get started?Download WordPress

Forums

Is prepare needed for insert query? (7 posts)

  1. Gregg Banse
    Member
    Posted 4 months 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.

    TIA.

  2. Jason
    Member
    Posted 4 months 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
    Member
    Posted 4 months ago #

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

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

    [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
    Member
    Posted 4 months ago #

    Apologies.

  5. Andrew Nacin
    Lead Developer
    Posted 4 months 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
    Member
    Posted 4 months ago #

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

  7. Gregg Banse
    Member
    Posted 4 months ago #

    For anyone that reads this thread these were helpful:

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

Reply

You must log in to post.

About this Topic