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.
wpdb->prepare
works, the whole point ofprepare
is to avoid joining strings and variables together. If you look at your PHP error log you should be seeing warnings that prepare wasn't given enough arguments. If you use prepare correctly, you should not needesc_like
$wpdb->prepare("SELECT * FROM table WHERE sku LIKE %s", $sku)
and result is still array (0), would you please elaborate which arguments I'm missing? Thanks%
whenwpdb
sends the parsed query to MySQL. So now that you've corrected theprepare()
syntax, with thatDCSS20MBJOF01HB
being the$sku
value, doesSELECT * FROM `table` WHERE `sku` LIKE 'DCSS20MBJOF01HB%' LIMIT 1
actually return any rows? And by that, I'm saying that if you get an empty array, then it's probably because there really are no rows matching the value of$sku
.prepare
syntax was wrong, and the data on the table was incomplete, due to a truncated csv import. Fixed both things, and now is working, thanks again!