plugins - Looping the data from WordPress database using foreach

admin2025-01-07  4

I am trying to fetch data from the WordPress database table using wpdb and loop it using foreach statement so as to output results in select tag. I created a custom WordPress template and this was to enable me to utilize the wpdb function. This query $worktype =$wpdb->get_results( "SELECT * FROM cww_avid_worktype;", OBJECT ); works fine when dump using print_r($worktype );, its return array results from the table hence means connection to the database is ok.

And the statement below works fine in pure PHP.

ISSUE When I loop $worktype using foreach it does not output any results or any error and I have turned on debug in wp-config. Foreach Loop

<select name="worktype" id="worktype" class="form-control required" >
<?php
global $wpdb;
$worktype =$wpdb->get_results( "SELECT * FROM cww_avid_worktype;", OBJECT );
foreach ($worktype as $val) {
if ($val->idworkType == $post['worktype']) {
echo '<option selected="selected" id="' . $val->idworkType . 'wt" value="' . $val->idworkType . '" title="' . $val->amount_added . '">' . $val->name . '</option>';
}
else {
echo '<option id="' . $val->idworkType . 'wt" value="' . $val->idworkType . '" title="' . $val->amount_added . '">' . $val->name . '</option>';
}
}
?>
</select>

I am trying to fetch data from the WordPress database table using wpdb and loop it using foreach statement so as to output results in select tag. I created a custom WordPress template and this was to enable me to utilize the wpdb function. This query $worktype =$wpdb->get_results( "SELECT * FROM cww_avid_worktype;", OBJECT ); works fine when dump using print_r($worktype );, its return array results from the table hence means connection to the database is ok.

And the statement below works fine in pure PHP.

ISSUE When I loop $worktype using foreach it does not output any results or any error and I have turned on debug in wp-config. Foreach Loop

<select name="worktype" id="worktype" class="form-control required" >
<?php
global $wpdb;
$worktype =$wpdb->get_results( "SELECT * FROM cww_avid_worktype;", OBJECT );
foreach ($worktype as $val) {
if ($val->idworkType == $post['worktype']) {
echo '<option selected="selected" id="' . $val->idworkType . 'wt" value="' . $val->idworkType . '" title="' . $val->amount_added . '">' . $val->name . '</option>';
}
else {
echo '<option id="' . $val->idworkType . 'wt" value="' . $val->idworkType . '" title="' . $val->amount_added . '">' . $val->name . '</option>';
}
}
?>
</select>
Share Improve this question asked Jul 10, 2020 at 6:22 DominicDominic 1011 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

I finally figure it out, I didn't call the method on instance correctly, inside the if statement if ($val->idworkType == $post['worktype']). I used this $post['worktype'] instead of this $post->worktype.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736259598a601.html

最新回复(0)