[英]Issue when converting mysql_fetch array to $wpdb->get results within WP Shortcode
I am looking to deliver a dropdown within the page of a Wordpress Theme connecting to the backend WP Database using $wpdb and ob_start to bring through option values.我希望在 Wordpress 主题的页面中提供一个下拉列表,该主题使用 $wpdb 和 ob_start 连接到后端 WP 数据库,以引入选项值。
In order to do this I have had to convert mysql_fetch array to $wpdb->get results and use a Shortcode generated from a PHP Snippet plugin.为了做到这一点,我不得不将 mysql_fetch 数组转换为 $wpdb->get results 并使用从 PHP Snippet 插件生成的简码。
Code -代码 -
add_shortcode( 'get-city', function () {
ob_start(); ?>
<?php
global $wpdb;
$results = $wpdb->query("SELECT countryid FROM {$wpdb->prefix}city");?>
<select name="city">
<option>Select City</option>
<?php while($row=$wpdb->get_results($results)) {
echo "<option value>{$row->city}</option>";
}
echo "</select>";
return ob_get_clean();
});
The shortcode shows no errors and is able to be activated.简码显示没有错误并且能够被激活。
The dropdown shows on the page but then no options are presented for a user to select. Nothing is being brought through from the db.下拉列表显示在页面上,但没有为用户提供任何选项 select。没有从数据库中获取任何内容。
I would really appreciate it if someone could point out the error.如果有人能指出错误,我将不胜感激。
Thanks in advance.提前致谢。
UPDATE -更新 -
I have amended 'while' to 'foreach' within the code -我已将代码中的“while”修改为“foreach”-
add_shortcode( 'get-city', function () {
ob_start(); ?>
<?php
global $wpdb;
$results = $wpdb->query("SELECT city FROM {$wpdb->prefix}city");?>
<select name="city">
<option>Select City</option>
<?php $rows = $wpdb->get_results($results); foreach( $rows as $row ){
echo "<option value>{$rows->city}</option>";
}
echo "</select>";
return ob_get_clean();
});
I still cannot bring values from the backend db.我仍然无法从后端数据库中获取值。
Many thanks for your response(s) so far.非常感谢您到目前为止的回复。
$wpdb->get_results($results)
is basically a fetchAll $wpdb->get_results($results)
基本上是一个 fetchAll
https://developer.wordpress.org/reference/classes/wpdb/get_results/
https://developer.wordpress.org/reference/classes/wpdb/get_results/
So do this所以这样做
add_shortcode( 'get-city', function () {
ob_start();
global $wpdb;
$results = $wpdb->query("SELECT city FROM {$wpdb->prefix}city");
?>
<select name="city">
<option>Select City</option>
<?php
$rows = $wpdb->get_results($results);
foreach( $rows as $row ){
echo "<option value='{$row->city}'>{$row->city}</option>";
}
echo "</select>";
return ob_get_clean();
});
You may want to put the id
of the ciry row in the value
attribute like this.您可能想像这样将 ciry 行的
id
放在value
属性中。 Depends on how its stored and later used取决于它的存储方式和以后的使用方式
echo "<option value='{$row->id}'>{$row->city}</option>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.