Using the same shortcode to show any table from the database

I have a little question for you.

I want to create a shortcode that makes a table with data that I have stored in a database. But i want to send the shortcode an attribute, to specify which table (database) I’d like to show.

Read More
add_shortcode("list", "list");

function list($tbl) {
    extract(shortcode_atts(array('item' => '')), $tbl);
    if($item!="") {
        $mydb= new wpdb('root','root','mydb','localhost');
        $rows = $mydb->get_results("select * from ".$item);
        echo "<table>";
        foreach ($rows as $obj) {
            echo "<tr>";
            //Here I want to put the content of the row
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<h2>blank</h2>";
    }
}

The shortcode would be something like this:

[list item="table1"]

How can I use the same shortcode to show any table of a database? How can I manage each row to show all the fields it has got? Because i have different tables with different number of columns and different column names, and i want to display each cell in a in the table.

Thanks!

Related posts

Leave a Reply

1 comment

  1. Just solved it!

    function list($tbl) {
        extract(shortcode_atts(array('item' => '')), $tbl);
        if($tbl["item"]!="") {
            $mydb= new wpdb('root','root','mydb','localhost');
            $rows = $mydb->get_results("select * from ".$tbl["item"].";",ARRAY_N);
            echo "<table>";
            for($i=0;$i<count($rows);$i++) {
                echo "<tr>";
                for($j=0;$j<count($rows[$i]);$j++) {
                    echo "<td>".$rows[$i][$j]."</td>";
                }           
                echo "</tr>";
            }
            echo "</table>";
        } else {
            echo "<h2>blank attr</h2>";
        }
    }
    

    If someone has a better answer please share!

    😀