如何在WordPress中将mysqli查询转换为$ wpdb? [英] How to convert a mysqli query to $wpdb in wordpress?
本文介绍了如何在WordPress中将mysqli查询转换为$ wpdb?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Wordpress表中使用$ wpdb查询而不是mysqli.
I want to use $wpdb query instead of mysqli for my wordpress table.
有问题的wordpress表如下:wp_example
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 |
+----+---------------------+------+
我希望放在$ wpdb中的mysqli查询:
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)\n", $row["name"], $row["age"]);
/* close connection */
?>
我开始自己尝试尝试一些东西,但被卡住了.
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));
希望有进一步的指导.
推荐答案
在主题的功能文件中,添加以下内容:
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();
这篇关于如何在WordPress中将mysqli查询转换为$ wpdb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文