Is it good practice to use wpdb->query() function?

I am using custom php code to perform data insertion, deletion, updating and other tasks. I am able to insert data into a table in two different ways,

$wpdb->insert($table_name, array('id' => NULL, 'name' => '$name', 'email' => '$email', 'city' => '$city'));

and

$sql = "INSERT INTO $table_name VALUES('', '$name', '$email', '$city')";
$wpdb->query($sql);

Is it a good practice to use wpdb->query() function each time by passing my query to the function instead of using the dedicated functions like insert() and delete() etc? If not, what are the disadvantages of this approach?

2 Answers
2

If you look a bit into the source, you’ll see that $wpdb->insert() will use ->query() under the hood. So should be the same, right?

Not that simple. It doesn’t just use ->query() but also ->prepare(), which is considered best practice. Meanwhile with your code example you’ve probably just opened yourself to SQL injections.

The takeaway here: If it is a simple operation and the ->insert() etc. method work – use them. They’re tested and contain little risk. Writing your own queries always carries the risk of opening yourself up to troubles such as SQL injections.

Leave a Comment