简体   繁体   中英

Wordpress custom database query

I am trying to get the result from the database with the mysql LIKE but in wordpress its not working here is the code of what i am trying

//this is what i am putting in where clause.
$state = $_POST['state'];
//table name.
$table_name = $wpdb->prefix . 'userprofile';
//trying but this is returning empty
$q = 'SELECT * FROM ' . $table_name . 'WHERE state LIKE \'%' . esc_sql( like_escape( $state ) ) . '%\'';
echo $q;
$result = $wpdb->get_results($q);
if (empty($result)) {
    echo "the result is empty";
}
//returns empty array.
print_r($result);

Like Marc B. said, there are some missing quotes and unnecessary quotations.. change your query line, to this:

$q = "SELECT * FROM $table_name
      WHERE state LIKE '%". esc_sql( like_escape( $state ) ) . "%'
      AND WHERE city LIKE '%". esc_sql( like_escape( $city ) ) . "%'
      AND WHERE session LIKE '%". esc_sql( like_escape( $session ) ) . "%'
      OR WHERE another LIKE '%". esc_sql( like_escape( $another ) ) . "%' ";

and your POST line to this:

$state = $_POST['state'];

You are missing a space:

$q = 'SELECT * FROM ' . $table_name . 'WHERE[..snip..]
                                       ^---here

which means you're producing

SELECT * FROM whateveruserprofileWHERE

which is invalid SQL.

do this way

$state = esc_sql( $state );

$state = like_escape( $state );

$state = '%' . $state . '%';

$q = 'SELECT * FROM ' . $table_name . 'WHERE state LIKE '$state';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM