简体   繁体   中英

Empty result of query in PHP , but when I run an SQL query from PHPMyAdmin, it works

Empty result of query in PHP (wordpress), but when I run an SQL query from PHPMyAdmin, it works ! And here is part of code, which returns empty array

<?php
global $wpdb; 
$from = $_POST['amount'];
$to = $_POST['amount1'];

$query = "SELECT  post_content
FROM `wp_postmeta`
INNER JOIN `wp_posts` ON wp_posts.ID = wp_postmeta.post_id
WHERE meta_key = 'product_price'
AND meta_value > '$from'
AND meta_value < '$to'";

$results = $wpdb->get_results($query);;
var_dump($results);  // empty array
?>

Anyone can explain my the problem ? Thanks !

I believe the reason for this is that the input to the clauses regarding the meta_value column are being treated as strings. You need to treat them as numerics.

Take a look at the 'query_posts' function in Wordpress.

$args = array(
  'meta_query'=> array(
    array(
      'key' => 'product_price',
      'compare' => '>',
      'value' => $from,
      'type' => 'numeric'
    ),
    array(
      'key' => 'product_price',
      'compare' => '<',
      'value' => $to,
      'type' => 'numeric'
    )
  )
  'posts_per_page' => 100
) );

query_posts( $args );

Alternatively, have your inputs treated as numerics, not strings. Remove the single quotes around them in your original query.

global $wpdb; 
$from = $_POST['amount'];
$to = $_POST['amount1'];

$query = "SELECT  post_content
FROM `wp_postmeta`
INNER JOIN `wp_posts` ON wp_posts.ID = wp_postmeta.post_id
WHERE meta_key = 'product_price'
AND meta_value > $from
AND meta_value < $to";

$results = $wpdb->get_results($query);
var_dump($results);

I still highly recommend you get in the habit of sanitizing your input.

An added benefit of the first solution, is that the query_posts function will automatically sanitize your input, based on the input type provided.

References:

I really care about security and all answers no one was concerned about it so I am adding the best solution for this because you should NEVER trust your inputs you need always to validate it.

Below should be a good working solution.

Also you should read this and this .

<?php
global $wpdb; 
$from = $_POST['amount'];
$to = $_POST['amount1'];

$query = "SELECT  post_content
FROM `wp_postmeta`
INNER JOIN `wp_posts` ON wp_posts.ID = wp_postmeta.post_id
WHERE meta_key = 'product_price'
AND meta_value > %d
AND meta_value < %d";

$results = $wpdb->get_results($wpdb->query($wpdb->prepare($query, $from, $to));
var_dump($results); 
?>

Make sure $from and $to have numeric values.

And then just remove the single quotes from the SQL query.

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