N
N
Newn2018-03-28 18:11:50
PHP
Newn, 2018-03-28 18:11:50

How to loop data from wpdb using shortcode?

Good afternoon people. I create a shortcode in wordpress.

function get_b_cf7_func() {
   global $wpdb;
   $table_name = $wpdb->prefix . 'sell';
   $user = wp_get_current_user()->user_login;
   $query = $wpdb->get_row("SELECT * FROM ".$table_name." WHERE user_name='".$user."'");
    return  $res_;

The task is to. it output all data of the logged in user from the database table. in html. An example is written below. Those. if it has many entries. It will display information for each column starting from a new line using a loop. I have read several articles on this site. But he couldn't figure it out. Thank you!
<div class='img_out_f'>
<div class='content'>
<div class='tbl'>Столбец 1</br></br>
        <div class='tbl'>строка 1</div>
        <div class='tbl'>строка 2</div>
</div>
<div class='tbl'>Столбец 2</br></br>
        <div class='tbl'>строка 1</div>
</div>
<div class='tbl'>Столбец 3</br></br>
        <div class='tbl'>строка 1</div>
</div>
<div class='tbl'>Столбец 4</br></br>
        <div class='tbl'>строка1</div>
</div>
<div class='tbl'>Столбец 5</br></br>
        <div class='tbl'>строка 1</div>
</div>
</div>
</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Newn, 2018-03-29
@Newn

Here is the solution to my question

function get_b_cf7_func() {
   global $wpdb;
   $table_name = $wpdb->prefix . 'sell';
   $user = wp_get_current_user()->user_login;
   $query = $wpdb->get_results("SELECT * FROM ".$table_name." WHERE user_name='".$user."'");
    $include_var = '';
  foreach ($query as $q ):
    $include_var .= "<tr><td>".$q->coin."</td><td>".$q->bank."</td><td>".$q->cours."</td></tr>";
    $str = "<table class='table'<thead><tr><th> Title </th><th>Content</th><th>Date</th></tr></thead><tbody>".$include_var."</tbody></table>";
    
endforeach;
  
  $str_ = $str;

    return  $str_;  
    
} 
    
add_shortcode('get_b', 'get_b_cf7_func');

L
leni_m, 2018-03-28
@leni_m

for example, if your data is received in this form $arr[$i]['столбец_1'], $arr[$i]['столбец_2'], ....
where $i corresponds to the lines in the database, then something like this:

<table>
<?php foreach($arr as $el): ?>
<tr>
   <td><?php echo $el['столбец_1']; ?></td>
   <td><?php echo $el['столбец_2']; ?></td>
   ....
</tr>
<?php endforeach; ?>
</table>

But I am not a clairvoyant in order to find out by the power of thought in what form your data is in your variables. And what you want to get is also not clear. Why are there 2 rows in the first column and only one in the rest? And why are you using divs if there is a ready-made tag <table>specifically for such data output.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question