I’m trying to get data from a custom table in a wordpress database, so I can show different stuff depending on the product visited (I use a variable for that) it’s a shop.
So far I have:
$sku = $wpdb->esc_like($product->get_sku())."%";
$sql = $wpdb->prepare('SELECT * FROM `table` WHERE `sku` LIKE "'.$sku.'"');
$result = $wpdb->get_results($sql);
var_dump($result);
And I get:
array(0) {
}
If I put a test sku instead of the variable, it returns results fine:
$sql = "SELECT * FROM `table` WHERE `sku` LIKE '%DCAT19%' LIMIT 1"; $result = $wpdb->get_results($sql); echo $sql; var_dump($result);
I get:
SELECT * FROM `table` WHERE `sku` LIKE '%DCAT19%' LIMIT 1
array(1) {
[0]=>
object(stdClass)#7675 (24) {
["id"]=>
string(1) "1"
["sku"]=>
string(17) "DCAT19MDIXHUEFL-L"
["fieldcount"]=>
string(1) "4"
...etc
But I need the variable to work, so it can change depending on the product visited.
NOW, if I echo the result from $sql, when using a variable, that is:
$sql = $wpdb->prepare('SELECT * FROM `table` WHERE `sku` LIKE "'.$sku.'"');
It gives a looong string instead of % (!!!):
SELECT * FROM `table` WHERE `sku` LIKE "DCSS20MBJOF01HB{0ff8bf1af1220a9d0556b6de44274e60e96a206d5cac40b1b55605b27fe76b4a}"
I have no idea what happens!! I think that’s breaking the query, maybe? No idea what to do next.
I’ve also tried (with variable):
- Double escape the %
- Quote the table and column names
- Calling the variable with %s
- Using sprintf
SAME RESULTS… array in zero and/or looong string instead of a %.
So, if someone could please let me know, what I’m doing wrong? Thanks a lot in advance.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Turns out prepare had bad syntax, and my table was incomplete due to a bad csv import. So, lesson learned, check the manual for syntax, and check (double check!) your tables. Thanks to Tom and Sally for their comments, they helped me to re-think what was I doing wrong.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0