user3805423
user3805423

Reputation: 23

Building a HTML table using MySQL/PHP results

I am trying to build a dynamic HTML table (regardless of number of columns or rows) from a MySQL query but I think I might be doing something wrong as it doesn't work at all.

I have experience with Oracle but I am new to MySQL. I have tried to check that the MySQL/PHP functions I am using do exist and I think that is the case.

<?php
$mysqli = new mysqli("localhost", "dbuser", "dbpass", "db");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM user")) {
    /* build html table */
    echo "<table class='table '><thread><tr>";

    $ncols = mysqli_num_rows($result);
    for ($i = 1; $i <= $ncols; $i++) {
        $column_name  = mysqli_field_name($result, $i);
        echo "<th>".$column_name."</th>";
    }

    echo "</tr></thread><tbody>";

    while ($row = mysqli_fetch_array($result, OCI_NUM)) {
        echo "<tr>";
        for ( $ii = 0; $ii < count($row); $ii++ ) {
            echo "<td>" . $row[$ii] . "</td>";
        }
        echo "</tr>";
    }

    echo "</tbody></table>";

    /* free result set */
    $result->close();
}

$mysqli->close();
?>

Appreciating any help!

Steve

Edit: I added the error reporting as suggested and get:

Fatal error: Call to undefined function mysqli_field_name() in connection.php on line 20

Upvotes: 0

Views: 1321

Answers (3)

Pradeep
Pradeep

Reputation: 1

<?php
$link=mysql_connect("hostname","username","password","dbname");
$query="select * from table_name";
$sql=mysql_query($query,$link);
if(count($sql)>0)
{
?><tr><th></th>
<?php

while($row=mysql_fetch_array($sql))
    { ?> 
           <tr><td><?php $row['columnname']; ?>
   <?php  } }?>

Upvotes: -1

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5899

Your basic problem is, that you probably converted from mysql_ functions to mysqli which is great! But there is no function mysqli_field_name() this function does just exist as a mysql_ function.

You need the mysqli_result::fetch_fields() function/method in mysqli to get the field names.

Upvotes: 2

Ralph
Ralph

Reputation: 3039

This should be a boolean operation not an assignment

if ($result = $mysqli->query("SELECT * FROM user"))

Upvotes: 0

Related Questions