I hope this is not redundant - but there always seems to be enough different that I cannot get things working.
I am building a function in my functions.php
file - all other functions work fine.
$query = $mydb->get_results("select * from table");
//This works just fine in mysql and I can do things like count(*) and get that to report back.
But for whatever reason I cannot get the table to return results that output to the wordpress page
return "$query";
return "$query[0]";
return "$query["wk"]";
The only output I get to have displayed on any page is the word Array where I am expecting the output to be.
So something like this works perfectly -
function VtVML_visitor(){
$home = get_field('home');
$visitor = get_field('visitor');
$mydb = new wpdb('OMMITTED');
$hWins = $mydb->get_var("SELECT count(*) FROM `table` where v = '$home' and h = '$visitor' and h_ml_win = 1");
$hLoss = $mydb->get_var("SELECT count(*) FROM `table` where v = '$home' and h = '$visitor' and h_ml_loss = 1");
$hTie = $mydb->get_var("SELECT count(*) FROM `table` where v = '$home' and h = '$visitor' and h_ml_tie = 1");
$vWins = $mydb->get_var("SELECT count(*) FROM `table` where h = '$home' and v = '$visitor' and v_ml_win = 1");
$vLoss = $mydb->get_var("SELECT count(*) FROM `table` where h = '$home' and v = '$visitor' and v_ml_loss = 1");
$vTie = $mydb->get_var("SELECT count(*) FROM `table` where h = '$home' and v = '$visitor' and v_ml_tie = 1");
$tWins = $vWins+$hWins;
$tLoss = $vLoss+$hLoss;
$tTie = $vTie+$hTie;
return "$visitor vs $home overall:<br>$tWins - $tLoss - $tTie";
$mydb -> close();
}
add_shortcode('VtVML','VtVML_visitor');
But if I repurpose this into a new shortcode and change the queries to pull specific fields:
$schedule = $mydb->get_var("SELECT wk,v,h FROM `table` where h = '$home'");
return "$schedule";
I see the error described above. I am assuming I need to do a foreach or while command - but all attempts to use these have not yielded results.
$wpdb->prepare
and have dynamic values inserted. Likewise you're embedding variables directly into HTML output without any escaping. You've also put the$mydb->close
after the return statement, so it will never be reachedreturn "$thing";
on its own should just bereturn $thing
, you don't need to wrap it in quotesprepare
is when the SQL query is static with no variables. Escaping takes all the uncertainty out of output by enforcing assumptions. e.g. if I doecho esc_url( $foo )
I will always get a URL, even if$foo
contains javascript or a ransom message. It might be a garbled URL, but it is guaranteed to be a URL