WordPress $wpdb prepare on external sql database

I’m trying to ensure my WordPress code is all safe from SQL injections and trying to use $wpdb->prepare() to ensure this. However, it doesn’t seem to be function correctly.

The code I am practicing with pulls data from a different SQL database on the same server (i.e not from the wordpesss database). The code I use is:

$mydb = new $wpdb('databese_username','password','datbasename', 'host');
$id = 2;
$users = $mydb->get_results( $mydb->prepare("SELECT table.column
                             FROM table.column
                             INNER JOIN table ON table.column = table.column
                             WHERE table.column = %d",$id));

This is fine for getting the data but it is not clear whether the prepare() is working and would stop sql injection if used in other ways. My concern is that I can easily change $id to a string (i.e $id = “2”; ) and the code still gets my data. Shouldn’t prepare stop this from working?

How do I properly use the prepare when using an external database? Is it $mydb->prepare() or should it be $wpdb->prepare() or something else?

Thanks


Source: wpdb

Leave a Reply