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
$_GETvariable in PHP. For instance:
$name = $_POST['name']; $email = $_POST['email'];
wpdb: Before you can use
wpdb, you’ll need to globalize it:
- Prepare the Query: Now you can use the
preparemethod of the
wpdbobject 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 );
%s in the query is a placeholder that will be replaced by the variables
prepare method automatically escapes these variables.
- Execute the Query: To execute the query, use the
This will run the query on your WordPress database. If it’s an
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.