getButterfly Logo getButterfly

How to replace a mysql_query with $wpdb->get_results in order to be safe from SQL injection and have your plugin work with WordPress multisite? I’ll just leave this here.

If you expect multiple results, use the following:

Suppose you have this chunk of code:

$result = mysql_query("SELECT * FROM mytable ORDER BY date ASC LIMIT 30");
while($row = mysql_fetch_array($result)) {
    echo $row['date'] . ' ' . $row['sent'];

You need to replace it with this one:

global $wpdb;

$results = $wpdb->get_results("SELECT * FROM mytable ORDER BY date ASC LIMIT 30", ARRAY_A);
foreach($results as $row) {
    echo $row['date'] . ' ' . $row['sent'];

If you expect a single result, use the following:

$rowcode = $wpdb->get_row("SELECT codename FROM mytable WHERE `codeID` = '1' LIMIT 1", ARRAY_A);
echo $rowcode['codename'];

If you need to count the results, use the following:

$items = $wpdb->get_results("SELECT * FROM mytable");
$items = $wpdb->num_rows;

It happens with old plugins. Updating them is just a breeze!
Expect lots of updates on my CodeCanyon items.

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a Reply

Your email address will not be published. Required fields are marked *