Melvin Koshy Melvin Koshy - 17 days ago 7
HTML Question

Table extraction from SQL dB

I have set up wamp server. I have uploaded a table named stud to phpMyAdmin under the database test. Now I want to display it in web browser as a table with lines as delimiters. I wrote the following code as a PHP. When I tried to run localhost/hw.php, the error is as follows:

<html>
<head>
<title>mysqli Table Viewer</title>
</head>
<body>
<?php
$db_host = 'localhost';

$database = 'test';
$table = 'stud';

if (!mysqli_select_db($database))
die("Can't select database");

// sending query
$result = mysqli_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}

$fields_num = mysqli_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";

// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";

// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";

// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";

echo "</tr>\n";
}

mysqli_free_result($result);
?>
</body>
</html>


How do I fix this error?

Answer

Before accessing the table you must connect to the database, this connection is necessary for all the operations over the database. In the next code I use arrows (// ◄■■■) to point to the changes (pay attention to the $cnx variable) :

<html>
<head>
<title>mysqli Table Viewer
</title></head><body>
<?php
$db_host = 'localhost';

$database = 'test';
$table = 'stud';

$cnx = mysqli_connect( $db_host, "root", "", $database ) //◄■■■■■■■■■■■■■■
       or die(mysqli_error($cnx));

if (!mysqli_select_db( $cnx, $database ) )               //◄■■■■■■■■■■■■■■
    die("Can't select database");

// sending query
$result = mysqli_query( $cnx, "SELECT * FROM {$table}" );  //◄■■■■■■■■■■■
if (!$result) {
    die("Query to show fields from table failed");
}

$fields_num = mysqli_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysqli_fetch_field($result);
    echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysqli_free_result($result);
?>
</body>
</html>
Comments