0

Hi Below is my query and it works with prepare keyword on the localhost but whenever I use prepare keyword with my queries on live server the data does not show up and as soon I remove prepare from query on live server the query works. So I did this to save my site from SQL injection. So if what is that I am doing wrong. Am I good and safe with prepare on live server because with prepare and my below syntax data shows empty always. Thanks people.

$sqll = "SELECT Sum(votes.votes) AS votessum FROM votes WHERE votes.uid = '$uid' && votes.competition = '$comp'";

     $reel = $wpdb->get_var($wpdb->prepare($sqll)) or die(mysql_error());
        echo json_encode ($reel);
        die();
  • What are you intending to do? In first line you concatenate SQL with unescaped values, and then you're trying to run prepare on this string... It makes no sense at all... – Krzysiek Dróżdż May 16 '15 at 4:56
  • Heay ... I am a bit confused about escaping in wordpress ... so what is the right way to do that ... there is also a function called esc_sql() and in codex page it is recommended not to use it when we use prepare. So what I am doing wrong here in the context of wordpress. @KrzysiekDróżdż I am just fetching data from database and will display them with echo below it ... just guide how I can imporove my query and make it safe and also standard .. thanks – Zeeshan May 16 '15 at 5:05
1

That is not how $wpdb->prepare works. You feed prepare a string with sprintf-like placeholders, and the appropriate replacement values.

Placeholders

The query parameter for prepare accepts sprintf()-like placeholders. The %s (string), %d (integer) and %f (float) formats are supported. (The %s and %d placeholders have been available since the function was added to core in Version 2.3, %f has only been available since Version 3.3.) Any other % characters may cause parsing errors unless they are escaped. All % characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as %%. All of %d, %f, and %s are to be left unquoted in the query string. Note that the %d placeholder only accepts integers, so you can't pass numbers that have comma values via %d. If you need comma values, use %f as float instead.

In your case, I am guessing that to look like:

$sqll = "SELECT Sum(votes.votes) AS votessum FROM votes WHERE votes.uid = %d && votes.competition = %s";
$reel = $wpdb->get_var($wpdb->prepare($sqll,$uid,$comp));
  • Ok great thanks ... that was of great help @s_ha_dum – Zeeshan May 16 '15 at 5:12

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.