dqdfpmmi022763 2016-09-28 23:03
浏览 76
已采纳

如何在WordPress中将mysqli查询转换为$ wpdb?

I want to use $wpdb query instead of mysqli for my wordpress table.

The wordpress table in question as follows : wp_example

+----+---------------------+------+
| id | name                | age  | 
+----+---------------------+------+
|  1 | Sandy Smith         | 21   |       
|  2 | John Doe            | 22   |        
|  3 | Tim Robbins         | 28   |         
|  4 | John Reese          | 29   |          
|  5 | Harold Finch        | 20   |       
+----+---------------------+------+

The mysqli query which I would like to be in $wpdb:

<?php
 // Make a MySQL Connection

$query = "SELECT * FROM wp_example";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)
", $row["name"], $row["age"]);

/* close connection */
?>

Reference 1
Reference 2

I started out to try something on my own but got stuck.

global $wpdb;
$query = $wpdb->get_results($wpdb->prepare("SELECT * FROM wp_example", ARRAY_A));

would love to have further guidance.

  • 写回答

1条回答 默认 最新

  • douan5151 2016-09-28 23:27
    关注

    In your theme's functions file, add this:

    function test_query() {
        // Global in the database
        global $wpdb, $table_prefix;
        // Set up the table name, ensuring you've got the right table prefix
        $table = $table_prefix . 'example';
        // For demo purposes, set up a variable
        $age = 21;
        // For TESTING ONLY, turn on errors to be sure you see if something goes wrong
        $wpdb->show_errors();
        // Use $wpdb->prepare when you need to accept arguments
        // Assign the query to a string so you can output it for testing
        $query = $wpdb->prepare( "SELECT * FROM {$table} WHERE age = %d", $age );
        // For TESTING ONLY, output the $query so you can inspect for problems
        var_dump( $query );
        // Get the results
        $results = $wpdb->get_results( $query );
        // Output the results
        foreach( $results AS $row ) {
            // Don't use ARRAY_A - just access as an object
            echo '<p>' . $row->name . '</p>';
            echo '<p>' . $row->age . '</p>';
        }
    }
    
    // Run your function
    test_query();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?