Here I want to fetch the field names from the table name which is stored in the variable $table. And want to make a table headers of the field names. What's wrong with this approach I tried:
<?php
$sql=mysql_query("show fields from $table");
if(mysql_num_rows($sql))
while($res = mysql_fetch_object($sql))
{
?>
<th><?php echo $res->field; ?></th>
<?
}
else
{
echo "No data to display";
}
?>
$printTHs = true;
while($res = mysql_fetch_assoc($sql))
{
if ($printTHs)
{
printTableHeader($res);
$printTHs= false;
}
echo "<tr>";
foreach($res as $val)
{
echo "<td>" . $val . "</td>";
}
echo "</tr>";
}
function printTableHeader($res)
{
echo "<tr>";
foreach($res as $col => $val)
{
echo "<th>" . $col . "</th>";
}
echo "</tr>";
}
The query has to be
$sql=mysql_query("show columns from $table");
Use mysql_fetch_assoc() and then get the keys using array_keys(). This will return an array with all the keys.
Use foreach() to get your table headers
Not the optimal solution, but would do it:
$results = mysql_query('SELECT * FROM ' . $table);
if (mysql_num_rows($results))
{
echo '<table>';
$first = TRUE;
while ($row = mysql_fetch_assoc($results))
{
if ($first = TRUE)
{
echo '<tr>';
foreach ($row as $k => $v)
echo '<th>' . $k . '</th>';
echo '</tr>';
$first = FALSE;
}
echo '<tr>';
foreach ($row as $column)
echo '<td>' . $column . '</td>';
echo '</tr>';
}
echo '</table>';
}
Related
I'm trying to show a full table from SQL in my HTML/PHP webpage. So far I succeeded to fetch the data from the table in my webpage without define each row in HTML. This works, but it shows the data from the table only. I want to see the column names in the first row.
See my code below:
include_once "connection.php";
$sql = "SELECT * FROM `own`";
$result = mysqli_query($conn, $sql);
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
As you are using mysqli_fetch_assoc() - this will return an array with the column names as the key for each value. So this code will display (for the first loop only) the column names as a separate row.
$headerDisplayed = false;
while ($row = mysqli_fetch_assoc($result))
{
if ( $headerDisplayed == false ) {
echo "<tr>";
foreach($row as $columnName => $value) {
echo "<th>" . $columnName . "</th>";
}
echo "</tr>";
$headerDisplayed = true;
}
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
If you want to be able to give a more meaningful name, you could also use column aliases (for example)..
select `dept_no` as `department number` from `departments`
will show department number as the heading instead of dept_no.
The easiest solution would be to just output the column names first on the first iteration:
while ($row = mysqli_fetch_assoc($result))
{
// If the variable $colNamesPrinted is undefined, print the column names
if (isset($colNamesPrinted) === false) {
echo "<tr>";
foreach($row as $name => $value) {
echo "<th>" . $name . "</th>";
}
echo "</tr>";
// Define the variable so it will be set on the next iteration.
$colNamesPrinted = true;
}
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
I have an SQL-database where I read out data that are then shown in a dynamically generated html-table. Here is my code that works fine:
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray";
$result = mysqli_query($db, $sql) or die("Invalid query");
$numrows = mysqli_num_rows($result);
$numcols = mysqli_num_fields($result);
$field = mysqli_fetch_fields($result);
if ($numrows > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) {
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
mysqli_close($db);
Now, I want to remove specific columns (e.g. those, which are empty or those, which are not that interesting for the user, who makes the request).
I tried it with unset($field[$variable]), however, it didn't work. In addition, the values (if there are any), should be removed, too.
can let mysql filter them out for you,
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray AND LENGTH($selection) > 0";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length
Always format the array before you print it. Try to remove the specific columns from the $field array before you echo the HTML and then print the final table. Once the HTML code is echoed in PHP you won't be able to remove it without the use of JavaScript.
You can check against the $field[$x]->name variable and use continue to skip the column.
<?php
// DataBase Config - http://php.net/manual/pt_BR/pdo.construct.php.
$dsn = 'mysql:host=localhost;dbname=test';
$usr = 'root';
$pwd = '';
try { // try to connect in database.
$pdo = new PDO($dsn, $usr, $pwd);
} catch (PDOException $e) { // if there is error in the connection.
die('Connection failed: ' . $e->getMessage());
}
// Prepare Statement and execute - http://php.net/manual/pt_BR/pdo.prepare.php.
$stm = $pdo->prepare('select id, weight, color, name from product');
$stm->execute();
// Get ALL rows - Object.
$rows = $stm->fetchAll(PDO::FETCH_OBJ);
// Print Rows.
//echo '<pre>'.print_r(rows, true).'</pre>';
// Check $row;
if (count($rows)) {
// Order and Display Cols.
$colsDisplay = [
'id' => 'ID Product',
'name' => 'Name',
'weight' => 'Weigth'
];
// Table.
$html = '<table border="1">';
$html .= "\n <thead>";
$html .= "\n <tr>";
$html .= "\n <th bgcolor='#eee'>Row</th>";
$html .= "\n <th>". implode("</th>\n <th>", $colsDisplay) ."</th>";
$html .= "\n </tr>";
$html .= "\n </thead>";
$html .= "\n <tbody>";
// Loop ROWS.
foreach ($rows as $key => $val) {
$html .= "\n <tr>";
$html .= "\n <td bgcolor='#eee'>". $key ."</td>";
// Loop COLS to display.
foreach ($colsDisplay as $thKey => $thVal) {
$html .= "\n <td>". $val->$thKey ."</td>";
}
$html .= "\n </tr>";
}
$html .= "\n".' </tbody>';
$html .= "\n".'</table>';
echo $html;
}
In order to know that a column is empty, you should check the whole column. There are different ways to do it, one of them could be investigating which of them are empty and then only using those that aren't empty. Something like this:
<?php
// ...
$q = "SELECT SUM(LENGTH(my_first_column)) col_0, SUM(LENGTH(my_second_column)) col_1, ..., SUM(LENGTH(my_11th_column)) col_10 FROM $tabelle WHERE $masterarray";
// ... execute query and return results in $nonEmpty
$nonEmpty = array();
foreach($row as $columnIndex) {
if ($row[$columnIndex] > 0) {
$nonEmpty[] = $columnIndex;
}
}
// ... now go through results and print only cols with at least one row with lenght > 0 i.e. non empty
$len = 11;
$rowHTML = "<tr>";
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $len; ++$i) {
$rowHTML = '';
if (!in_array($i, $nonEmpty)) {
$rowHTML .= '<td>' . $row[$i] . '</td>';
}
$rowHTML .= "</tr>\n";
}
}
// ...
This chunk of code will remove columns with ALL empty values. If you have at least one cell in the column with some value, you'll see the column in your result.
The code isn't optimized - it's just a rough idea. But it's a starting point.
I have the below code to show all data from a MySQL database in a HTMl database:
<?php
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>";
$i = 0;
while($row = $result->fetch_assoc())
{
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
This code works fine and the data is displayed in the table correctly, my problem is that most of the data in the DB is encrypted (simply)!
For example, here is how someones first name is stored 5cGs+mhdNN/SnHdqEbMk6zlKRu8uW7pR1zRjQHV9DGQ=
Is there a way to decrypt the data before displaying it in the table?
I usually decrpyt the date in the following way:
$name_firstD = simple_decrypt($name_first , "secured");
You need to have an array of columns which are encrypted.
<?php
$result = mysqli_query($con,"SELECT * FROM Persons");
$encrypted_columns = array('password','code', 'first_name');
echo "<table border='1'>";
$i = 0;
while($row = $result->fetch_assoc())
{
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>" . (in_array($key,$encrypted_columns))? simple_decrypt($value , "secured") : $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
put the name of your encrypted column inside $encrypted_columns array.
I am trying to get the column names and data from a table using mysqli and php. Any help is appreciated.
I know how to do this in java by more or less this code:
String [] header= new String[numberOfColumns-1];
//Code to get column names in header array
String table = "<table><tr>"
for(int i=0;i<numberOfColumns-1;i++){
table= table + "<td>" + header[i] + </td>;
}
table = table + </tr>;
while(result.next()!=null){
table = table + <tr>
for (int j = 0 ; j < numberOfColumns-1 ; j++){
table = table + <td> + result.getString[j] + </td>
}
table = table + </tr>
}
But i have no idea how to do it in php. Each table is different but what i have to far for the one table:
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>Last Name</td>";
echo "<td>Date of Birth</td>";
echo "<td>Contact Details</td>";
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $rowitem['fname'] . "</td>";
echo "<td>" . $rowitem['lname'] . "</td>";
echo "<td>" . $rowitem['dob'] . "</td>";
echo "<td>" . $rowitem['contact'] . "</td>";*/
echo "</tr>";
}
echo "</table>"; //end table tag
EDIT: Is the implementation of the fetch_fields correct?
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>"
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
for($x =0; $x < count($finfo);$x++){
echo "<td>" . $rowitem[$x] . "/td";
}
echo "</tr>";
}
echo "</table>";
EDIT 2: Database Connection.php
<<?php
include("config.php");
session_start();
$sql = ($_GET['q']);
$result = mysqli_query($db,$sql);
echo "<table border='1' class='table_info'>";
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>";
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
foreach ($row as $value) { (line 18)
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>"; //end table tag
?>
Error:
Notice: Undefined variable: row in databaseConnection.php on line 18
Warning: Invalid argument supplied for foreach() in databaseConnection.php on line 18
You can call mysqli_fetch_fields on the $result object, and retrieve the name property for each object in the returned array. See documentation for examples.
There are a couple ways to do this:
Use array_keys() to grab the names of the keys from an associative array:
$rowitem = mysqli_fetch_array($result, MYSQLI_ASSOC);
$header = array_keys($rowitem);
Use mysqli_fetch_fields() to grab the field objects, and parse out the names into an array using array_map():
// Helper function to use in array_map
// (For PHP < 5.3. If >= 5.3.0, use the second version)
function getFieldName($field) { return $field->name; }
// For PHP < 5.3:
$header = array_map("getFieldName", mysqli_fetch_fields($result));
// For PHP >= 5.3.0:
$header = array_map(function($o) { return $o->name; }, mysqli_fetch_fields($result));
As mentioned you can use $result->fetch_fields() to get the field information from the result and this includes the name of each field.
For what you're trying to acheive this code should work for pretty much any table/query:
<?php
/* Connect to mysql */
$mysqli = new mysqli("localhost", "username", "password", "database");
/* Check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Your query */
$query = "SELECT * from table";
if ($result = $mysqli->query($query)) {
/* Output HTML table */
echo "<table border='1'>";
/* Get field information for all returned columns */
$finfo = $result->fetch_fields();
/* Output each column name in first table row */
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>".$val->name."</td>";
}
echo "</tr>";
/* Fetch the result and output each row into a table row */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
$result->free();
echo "</table>";
}
$mysqli->close();
(Obviously you should never query a database from a $_POST variable without some serious sanitisation of the input, but I'll assume that was just for your convenience.)
You can Echo in a table..
$result = mysqli_query($db,$sql)
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysqli_num_fields($result);
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);`
I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>