hey guys i'm somewhat a beginner in wordpress, and wrote my own theme now

Question: what is the proper way of doing a sql query to a custom mysql table in combination with POST Data.

The problem is, that the data are getting double escaped, and i've no idea how to avoid this:

The following scenario:

an input comes via ajax

The input value: example'with'quotes

Worpress autoescapes in wp-settings.php the post array using wp_magic_quotes()

After that the input looks like: example\'with\'quotes

If i try to print out the last query via $this->wpdb->last_query in my Products_Model it shows something like

SELECT * FROM product WHERE name = 'example\\\'with\\\'quotes'

which shouldn't be happen ;)

My Code - what i've tried so far

functions.php (excerpt)


AppWpActions.php (excerpt)

class AppWpActions
    public function __construct()

    private function addSiteActions()
        add_action('wp_ajax_nopriv_web_products', [$this, "showProducts"]);
        add_action('wp_ajax_web_products', [$this, "showProducts"]);

    public function showProducts()
        $objProduct = new Product();


Product Class

class Product
    public function setAjaxList()
        $objProduct = new Product_Model();
        $arrData = $objProduct->getProducts($_POST['search']);
        header('Content-Type: application/json');
        echo json_encode($arrData);

Product Model

class Product_Model
    private $wpdb;
    private $arrStatusMessages = [];

    public function __construct()
        global $wpdb;
        $this->wpdb = $wpdb;

    public function getProducts($strSearch = "")
        if (!empty($strSearch))
            $arrData = $this->wpdb->get_results($this->wpdb->prepare("
                SELECT *
                FROM product
                    name = %s
            ", $strSearch));

            return $arrData;
            return [];


thx in advance for your answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.