0

When running the following code :

$voucher = 'MK0186';
$is_in_database = $wpdb->get_results( "SELECT * FROM my_codes_table WHERE code =" . $voucher );

I get : WordPress database error: [Unknown column 'MK0186' in 'where clause']. I don't understand why.

  • 1
    Aside from the complete lack of sanitisation, this is an SQL issue, not a WordPress issue, and is offtopic – Tom J Nowell Apr 11 '13 at 17:17
  • 1
    Also wrap your values in quotes, you will want to look at the WPDB classes prepare method – Tom J Nowell Apr 11 '13 at 17:18
  • I think it's a question & answer website, not a question & criticism website :) I still don't know what the solution to my particular problem is. – drake035 Apr 11 '13 at 17:23
  • @TomJNowell effectively answered your question already - wrap your value in quotes. Criticism is often part of an honest answer. And yes, this is off-topic. – vancoder Apr 11 '13 at 17:41
  • 1
    @drake035 your code is not perfect, perfect code does not exist, and criticism is helpful. I suggest you grow thicker skin and go to the SQL and Database exchange site where this question would be on topic – Tom J Nowell Apr 11 '13 at 18:39
2

The WPDB prepare method is what you're after, as this will prep your data for passing to a query and also ensure data matches the type its intended to be whilst also handling quoting where necessary at the same time.

Fixing your code could be a matter of..

$voucher = 'MK0186';
$is_in_database = $wpdb->get_results( "SELECT * FROM my_codes_table WHERE code = '$voucher'" );

.. but you'd be better advised to write it this way ..

$voucher = 'MK0186';

$is_in_database = $wpdb->get_results( 
    $wpdb->prepare( "
        SELECT * FROM my_codes_table 
        WHERE code = %s", 
        $voucher 
    ) 
);

Example query with 2 numeric values and a string value.

$num1 = 5;
$num2 = 10;
$string = 'Some String!!';
$query = $wpdb->get_results( 
    $wpdb->prepare( "
        SELECT * FROM sometable 
        WHERE column1 = %d 
        AND column2 = %d
        AND column3 = %s
        ", 
        $num1, $num2, $string
    ) 
);

In short... your string value isn't quoted, that's the issue. Use the $wpdb->prepare method and it'll take care of that for you.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.