这里我有这个查询,如果我将%f和%d的值替换为1和1,它将在我的phpmyadmin面板中工作但我通过wpdb get_results运行此查询并准备它不起作用。所有值都正确传递但仍然是输出null。
$f = $wc * (($ul + 100)/100);
$capabilities = $wpdb->prefix."capabilities";
$sql = "
SELECT u.*, up.*, up.pid, ( up.ros - up.soh ) / ( %f ) as qty_suggested
FROM $wpdb->users u
INNER JOIN wp_deals_users_products up
ON u.ID = up.user_id
INNER JOIN $wpdb->usermeta um
ON u.ID = um.user_id
WHERE up.pid = %d
AND um.meta_key = '$capabilities'
AND um.meta_value LIKE '%subscriber%'
";
//echo $sql; This echoes the sql which I tested in phpmyadmin sql query runner
$results = $wpdb->get_results(
$wpdb->prepare(
$sql,
$f,
$pid
)
);
echo json_encode($results);
如果我直接删除prepare并运行查询,或者使用硬编码1作为%d和%f的值,我仍然会得到null。相同的查询在phpmyadmin sql部分中可以正常工作
编辑:
这是wpdb prepare function中的最终查询:
SELECT u.*, up.*, up.pid, ( up.ros - up.soh ) / ( %f ) as qty_suggested
FROM wp_users u
INNER JOIN wp_deals_users_products up
ON u.ID = up.user_id
INNER JOIN wp_usermeta um
ON u.ID = um.user_id
WHERE up.pid = %d
AND um.meta_key = 'wp_capabilities'
AND um.meta_value LIKE '%subscriber%'
答案 0 :(得分:2)
您在LIKE
附近使用了错误的语法。
你必须这样使用。
$like_str = 'subscriber';
$f = $wc * (($ul + 100)/100);
$capabilities = $wpdb->prefix."capabilities";
$sql = "
SELECT u.*, up.*, up.pid, ( up.ros - up.soh ) / ( %f ) as qty_suggested
FROM $wpdb->users u
INNER JOIN wp_deals_users_products up
ON u.ID = up.user_id
INNER JOIN $wpdb->usermeta um
ON u.ID = um.user_id
WHERE up.pid = %d
AND um.meta_key = '$capabilities'
AND um.meta_value LIKE %s";
$query = $wpdb->prepare( $sql,$f,$pid,'%' . $wpdb->esc_like($like_str) . '%');
$result = $wpdb->get_results($query);
echo json_encode($result);
答案 1 :(得分:0)
看起来valirables $f
和$pid
的值未正确显示。
打印出最终查询以查看变量是否正确传递给' $ sql'像这样:
$sql = "
SELECT u.*, up.*, up.pid, ( up.ros - up.soh ) / ( %f ) as qty_suggested
FROM $wpdb->users u
INNER JOIN wp_deals_users_products up
ON u.ID = up.user_id
INNER JOIN $wpdb->usermeta um
ON u.ID = um.user_id
WHERE up.pid = %d
AND um.meta_key = '$capabilities'
AND um.meta_value LIKE '%subscriber%'
";
echo $sql;
调试$ sql并尝试使用phpmyadmin获取的查询。