【问题标题】:How to convert a mysqli query to $wpdb in wordpress?如何在 wordpress 中将 mysqli 查询转换为 $wpdb?
【发布时间】:2017-02-07 02:36:27
【问题描述】:

我想对我的 wordpress 表使用 $wpdb 查询而不是 mysqli。

有问题的wordpress表如下: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   |       
+----+---------------------+------+

我想在 $wpdb 中的 mysqli 查询:

<?php
 // Make a MySQL Connection

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

/* close connection */
?>

Reference 1
Reference 2

我开始自己尝试一些东西,但被卡住了。

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

希望得到进一步的指导。

【问题讨论】:

  • 如果你只想拥有 SQL "SELECT * FROM wp_example",那不应该在准备好的语句中。如果 SQL 中有变量,您只需要准备好的语句。你只会有$query = $wpdb-&gt;get_results("SELECT * FROM wp_example", ARRAY_A);

标签: php mysql wordpress mysqli


【解决方案1】:

在主题的函数文件中,添加以下内容:

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();

【讨论】:

  • 这太棒了,简洁明了,一切都很重要!我自己无法弄清楚。还有一件事,我可以用这个修改后的格式吗foreach( $results AS $row ) { $user_name = $row-&gt;name; $user_age = $row-&gt;age; }
  • 是的,您可以在该循环中做任何您喜欢的事情 - 回显、分配给变量或操作!
猜你喜欢
  • 2012-05-03
  • 2012-08-14
  • 2011-06-16
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
  • 2015-09-25
相关资源
最近更新 更多