How to make SQL-injection proof calls to custom table I have created in my WordPress Database?

So here is what im trying to accomplish: I have worked with SQL plenty of times in the past, but it was always with coldfusion, never with PHP. I have looked over the syntax for making sql queries and have come up with this much (i do believe that using prepare helps protect against sql-injection). My overall goal is to have a page set up to where it pulls all the rows from the jewelry table that has the cat_id corresponding with the categories table. Im just not sure if im starting this off correctly or not. The jewelry table has 4 fields (id, cat id, name, and image)

<?php

 $categorys = $wpdb->get_results ( $wpdb->prepare("SELECT id FROM $wpdb->categories
        WHERE name = '(the_slug())'") );

    $jewelrys = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->jewelry
        WHERE post_status = 'publish'
        AND cat_id = $categorys->id ") );

    foreach ($jewelrys as $jewelry) {
    echo '<div id="jBox"><a href="/wp-includes/images/jewelryImages/' . $jewelry->image . '"><img src="/wp-includes/images/jewelryImages/' . $jewelry->image . '" /><br />' . $jewelry->name . '</div>';
    }
?>

Also i am looking to adding pagination displaying only 9 per page. Any tips or guidance is greatly appreciated =)

Read More

Update:
I just tested the category with a simple echo statement to see if it pulled anything, and it didn’t, is this coded wrong?

Related posts

Leave a Reply

1 comment

  1. To avoid SQL injection, use prepared statements – that way you can pass your variable terms to MySQL as parameters (which it knows not to evaluate for SQL) rather than making them part of your SQL command.

    See How can I prevent SQL injection in PHP?

    To implement pagination, you want to look into MySQL’s LIMIT clause – e.g.

    SELECT ... LIMIT  0,9;  -- get 9 records starting from record 0
    SELECT ... LIMIT  9,9;  -- get 9 records starting from record 9
    SELECT ... LIMIT 18,9;  -- get 9 records starting from record 18
    -- etc