最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do you build a wpdb query dynamically?

programmeradmin2浏览0评论

My table has 6 columns, 3 of which I'm interested in: id, name, email. The problem is that my query does care about the name, but doesn't always care about email or id.

As of now, the code is this:


  function get_people( $name, $id = null, $name = null) {

    global $wpdb

    $table_name = $wpdb->prefix . 'my_table';

    $query = "SELECT * FROM $table_name WHERE name='%s'";

    if(!is_null($id)) {
        $query .= "AND id='%s'";
    }

    return $wpdb->get_results($wpdb->query(
        $query,
        $id
    ));
  }

However, WP is telling me this: wpdb::prepare was called incorrectly. The query does not contain the correct number of placeholders (1) for the number of arguments passed (3). Please see Debugging in WordPress for more information. (This message was added in version 4.8.3.)

And, of course, the query looks really ugly and not dynamic at all. If I want changes, it'd be hell to make it work.

Any ideas?

发布评论

评论列表(0)

  1. 暂无评论