WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] $wpdb->prepare and Bind values (3 posts)

  1. Derzone
    Member
    Posted 2 years ago #

    Hi there !

    I would like to bind values in a $wpdb->prepare query, but I really don't know how to do this.

    For exemple :

    // Values
    $bindValues = array('value1', 'value2');
    
    // SQL Query
    $select = $wpdb->get_results(
    	$wpdb->prepare(
    			SELECT COUNT(ID) AS total,
    			MATCH (display_name) AGAINST ('%s') AS score
    			FROM wp_users
    			WHERE MATCH (display_name) AGAINST ('%s') HAVING score > 0,
    			implode(',', $bindValues)
    		      );

    This of course doesn't work, so is there any functions / solutions to do it ?

    Thank's by advance.

  2. TCBarrett
    Member
    Posted 2 years ago #

    $select = $wpdb->get_results(
    	$wpdb->prepare(
    			"SELECT COUNT(ID) AS total,
    			MATCH (display_name) AGAINST ('%s') AS score
    			FROM wp_users
    			WHERE MATCH (display_name) AGAINST ('%s') HAVING score > 0",
    			value1, value2)
    		      );

    http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks

  3. Derzone
    Member
    Posted 2 years ago #

    Yep tcbarrett, I know this way to make prepared queries, but my question was about binding an unknown number of values.

    My example was quite naive, cause it doesn't really reflect what I meant.

    My query can be an unknown number of "SELECT", and so an unknown number of values. That's why I need to put them in an array.

    But after some tries I finally managed to do so, just by adding my array as a value, without "implode" or anything else :

    // Values
    $bindValues = array('value1', 'value2');
    
    // SQL Query
    $select = $wpdb->get_results(
    	$wpdb->prepare(
    			SELECT COUNT(ID) AS total,
    			MATCH (display_name) AGAINST ('%s') AS score
    			FROM wp_users
    			WHERE MATCH (display_name) AGAINST ('%s') HAVING score > 0,
    			$bindValues
    		      );

    The only thing is that you can't bind the array with others values like :

    SELECT COUNT(ID) AS total,
    			MATCH (display_name) AGAINST ('%s') AS score
    			FROM wp_users
    			WHERE MATCH (display_name) AGAINST ('%s') HAVING score > 0,
    			$bindValues,
    			$value3,
    			$value4,
    			...

    You have to put all of them in one array.

Topic Closed

This topic has been closed to new replies.

About this Topic