简体   繁体   中英

PHP Variables inside SQL WP Query

I'm using wordpress and i've created some custom functions. They work fine and now I'm at a point of adding sorting into the query.

function select_category_events($category, $order)  {
    global $wpdb;
    $table_name = $wpdb->prefix."table";
    $sql = $wpdb->get_results("select * from $table_name where category = '" . $category . "' AND  active = '1' ORDER BY '" . $order . "'");
    return $sql;
}

If I remove the ORDER BY and just have:

$sql = $wpdb->get_results("select * from $table_name where category = '" . $category . "' AND  active = '1'");

It works fine. If I replace $order with 'name' or a field to sort by, it works fine, its just when I pass it in using the variable it just ignores it. It still displays results, they are just unsorted. Here is how I'm calling the function.

$order = 'name';
$events = select_category_events($category, $order);

$category has a valid category, as I've said, it works fine, it's just when the variable is being used for the sort. Is my syntax incorrect, or should I be going about this in a different way?

删除引号,您要按列而不是按字符串排序

ORDER BY $order 

No Issue, please modify your query as :-

"select * from $table_name where category = '$category'  AND  active = '1' ORDER BY '$order' ";

If it is working fine then please mark it as answer and if not then please inform me what are you getting after running this query...

您必须使用这样的查询:-

$sql = $wpdb->get_results("select * from $table_name where category = '" . $category . "' AND  active = '1' ORDER BY " . $order);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM