我想在我的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 */
?>
我开始尝试自己的东西,但却陷入困境。
global $wpdb;
$query = $wpdb->get_results($wpdb->prepare("SELECT * FROM wp_example", ARRAY_A));
希望得到进一步的指导。
答案 0 :(得分: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();