Using the WordPress wpdb
class is a reliable way to interact with your database safely and effectively. When preparing an SQL string from a form, it’s vital to properly sanitize and escape the data to prevent SQL injection attacks.
Here is how you can do it:
- Obtain Form Data: First, you’ll need to obtain the data from your form. This will typically be done through a
$_POST
or$_GET
variable in PHP. For instance:
$name = $_POST['name']; $email = $_POST['email'];
- Globalize
wpdb
: Before you can usewpdb
, you’ll need to globalize it:
global $wpdb;
- Prepare the Query: Now you can use the
prepare
method of thewpdb
object to create your SQL string. This method will automatically escape your data to protect against SQL injection. Here’s an example:
$query = $wpdb->prepare( "INSERT INTO `my_table` (`name`, `email`) VALUES (%s, %s)", $name, $email );
The %s
in the query is a placeholder that will be replaced by the variables $name
and $email
. The prepare
method automatically escapes these variables.
- Execute the Query: To execute the query, use the
query
method ofwpdb
:
$wpdb->query($query);
This will run the query on your WordPress database. If it’s an INSERT
, DELETE
, or UPDATE
query, it will return the number of rows affected. For a SELECT
query, it will return an array of results.
So, the entire code snippet may look like this:
$name = $_POST['name']; $email = $_POST['email']; global $wpdb; $query = $wpdb->prepare( "INSERT INTO `my_table` (`name`, `email`) VALUES (%s, %s)", $name, $email ); $wpdb->query($query);
Remember, if your form is publicly accessible, it’s recommended to use WordPress nonces to verify the source of the request for additional security.