Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How am I supposed to use prepared statements in Wordpress with variables in a query?

I'm currently learning Wordpress and PHP, I'm also using WooCommerce. I currently have a form with three input fields, and I would like to check if the user inputted data about their order is true so the user can proceed to the next page.

My current code looks like this, and I am not sure if I am even going the right direction here, any help?

if(isset($_POST['submit'])) {
global $wpdb;

$ordernumber = $_POST['ordernmbr'];
$orderfirstname = $_POST['firstname'];
$orderpostnumber = $_POST['postnmbr'];

$ordernumber = stripslashes_deep($ordernumber);
$orderfirstname = stripslashes_deep($orderfirstname);
$orderpostnumber = stripslashes_deep($orderpostnumber);


$result = $wpdb->get_results($wpdb->prepare( "SELECT * FROM         $wpdb->wp_postmeta
  WHERE post_id = '$ordernumber' AND meta_value = '$orderfirstname'"));
like image 400
Puppe Avatar asked Dec 18 '25 10:12

Puppe


1 Answers

You can do it using prepare:

$sql = 'DELETE FROM `wp_table` WHERE `id_field` = %d';
$wpdb->query($wpdb->prepare($sql, array($_POST['id']))

Good things to know:

%d - number
%s - string
%f - float

the array of passed variables works in sequential order, so if you had a query like:

SELECT * FROM `wp_table` WHERE `string_field` = %s AND `id_field` = %d

you'd do

array(
    $_POST['string'],
    $_POST['id']
)

if it's a DELETE/UPDATE use query and prepare. If a select use prepare and get_results.

SELECT:

$sql = 'SELECT * FROM `wp_table` WHERE `id` = %d';
$sql = $wpdb->prepare($sql, array($_POST['id']));
$res = $wpdb->get_results($sql);
like image 61
treyBake Avatar answered Dec 20 '25 01:12

treyBake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!