WordPress Query Not Working – No Error – Query Fine otherwise

I have a $wpdb query I’m trying to execute, but it’s not going through and is throwing no error:

$followups = 
    $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM orders 
                WHERE status_id = %d
                AND DATEDIFF(CURDATE(), date_waiting_pickup) % 7 = %d",
                array(66, 0)
            )
        );

Any idea why? It runs fine in Terminal / direct MySQL. Is it the DIFFDATE() function?

Read More

EDIT: And interestingly enough, if I remove the $wpdb->prepare function, and leave $wpdb->get_results(), it works fine. So is there something I’m missing as far as how $wpdb->prepare() works?

Related posts

Leave a Reply

1 comment

  1. In case that you want, as it seems, orders in the last week… Why don’t you simplify it? There is no need for the second %d just put 0.

    $followups = 
        $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM orders 
                    WHERE status_id = %d
                    AND DATEDIFF(CURDATE(), date_waiting_pickup) % 7 = 0",
                    66
                )
            );
    

    UPDATE:

    @dtj You are using mod (%) operator that give us the remainder of the division. So comparing with 0 (my first assumption) we obtain orders from today, 1 week ago, 2 week ago, etc.. If we compare with 1 (in the second %d) we obtain orders form yesterday, 8 days ago, etc…

    Is really that what you want?

    UPDATE 2: In your edited question you say that removing $wpdb->prepare() all works fine. No doubt is interesting, but fortunately you really don’t need prepare() if you just works with integer numbers. I mean doing:

    $status_id = (int) (is_numeric($status_id) ? $status_id : 0);
    
    $followups = $wpdb->get_results("
        SELECT * FROM orders
        WHERE status_id = $status_id
        AND DATEDIFF(CURDATE(), date_waiting_pickup) % 7 = 0");
    

    you assure a safe query and gain in simplicity and efficiency. In my case I only use prepare() if there are strings involved and always test integer numbers as showed.