3

I struggle to echo content of certain columns from certain tables depends on user selection - for now I had only one table and code below work perfect but certainly other tables don't have same col names and values so I try to modify it - so far I'm stuck.How can I make it dynamic?

humble ask for some help :)

<?php
function showTables($table, $order) {
    global $conn;
    $query = ("SELECT * FROM $table ORDER BY $order ASC LIMIT 0, 30 ");
    $returnTables = mysqli_query($conn, $query);

    while ($row = mysqli_fetch_assoc($returnTables)) {
        $id = $row['id'];
        $name = $row['name'];
        $surrname = $row['surrname'];
        $email = $row['email'];
        $firstTime = $row['firstTime'];
        $comment = $row['comment'];

        echo "<tr>";    
            echo "<td>$name</td>";
            echo "<td>$surrname</td>";
            echo "<td>$email</td>";
            echo "<td>$firstTime</td>";
            echo "<td>$comment</td>";         
            echo "<td class='no-print'><a href='admin.php?delete={$id}'>Usuń</a></td>"; 
        echo "</tr>";
    }
}
?>
2
  • you can pass one more parameter as $fields in showTables() function and according to $fields you can dynamically get the result. Commented Mar 16, 2016 at 5:55
  • than use mysqli_fetch_array() and use numeric index Commented Mar 16, 2016 at 5:56

1 Answer 1

4

Simple get columns name from your TABLE,

eg,

$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);

while($row = mysqli_fetch_array($result)){
  echo $row['Field']."<br>";
}

EDIT 2 :

Complete Dynamic example( need to format tr and td )

function showTables($table, $order) {

    global $conn;

    $query = "SELECT * FROM $table ORDER BY $order ASC LIMIT 0, 30 ";
    $returnTables = mysqli_query($conn, $query);

    $sql_columns_name = "SHOW COLUMNS FROM $table";

    $sql_columns_result = mysqli_query($conn,$sql_columns_name);

    $column_arr = array();

    while($row = mysqli_fetch_array($sql_columns_result)){
      $column_arr[] = $row['Field'];
    }

    echo '<table>';

    while ($row = mysqli_fetch_array($returnTables)) {

        for ($i=0; $i < count($column_arr); $i++) {
            echo "<tr>";  
              echo "<td>".$row[$column_arr[$i]]."</td><br>";
            echo "</tr>";
        }

    }

    echo '</table>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Bhai user name kadak hai

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.