Can I display query results without naming columns? - php

Is there a php or html code to dynamically generate a table.
query :
"SELECT * FROM table1;
Can I display this grid of info without any specifics.
IF there are 4 rows and 4 columns I want the table to be that size; if 5x5 than that.
It seems like this should be possible, but all code I can find wants me to specify names or columns.

Yes. There are a couple different ways to do this, but for illustration I will assume that the result of your query is stored in a variable called $results, which is simply a multidimensional array that you can loop through using a double foreach to dynamically produce your table.
echo '<table>';
foreach ($results as $row) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';
OR if you don't have a $results array and are instead getting query results and building the table at the same time, something like this might be more appropriate for your needs:
echo '<table>';
while ($row = mysqli_fetch_array($query)) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';

echo'<table>';
while($row = mysql_fetch_array($result))
{
echo'<tr>';
echo '<td>'.$row[colname].'</td>';
echo '</tr>';
}
echo'</table>';

Related

MySQL row being outputted twice

I need to output a name from the last added row of my table, and it works sort of, it outputs the correct data twice. So instead of name1 it gives me name1name1. I'm still a novice with PHP but i think there is a double loop somewhere in this piece of code which is giving me a hard time, but i'm still unable to locate where that is..
If someone can give me a pointer that would be greatly appreciated.
<?php $query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
} ?>
By default, mysql_fetch_array() returns values both as associative and as enumerated (MYSQL_BOTH); specify either one or the other
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
EDIT
But the mysql extension is old and deprecated, and you really should be switching to mysqli or pdo with prepared statements and bind variables. If you're just learning, then it's best to learn the right methods with the right extensions from the start
No need of the while. You are fetching a single row. And use mysql_fetch_assoc for associative array
$row = mysql_fetch_assoc($results);
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
I would use mysql_fetch_assoc. Because this will only fetch the results as an associative array.
$query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}

Mysql rows to html table using for loop

I tried to print the Mysql fetched rows into html table using php. However, when using the following code, the first fetched row is repeatedly printing. It looks like the $row hold the first fetched value. I found a similar problem here. But I would like to know about working with the for loop. Thanks
for ($j=0;$j<=$len2;$j++)
{
$sql = "SELECT * FROM database_search WHERE gene_id LIKE'%$key%'";
$qry = $dbo->prepare($sql);
$qry->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
$val = array_values($row);
echo "<tr>";
for ($k=0;$k<=4;$k++)
{
$x=$val[$k];
echo "<td style=font-size:7.9px>$x</td>";
}
echo "</tr>";
}
<table>
<?php
while($row = $qry->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
foreach($row as $cell){ echo '<td>'.$cell.'</td>'; }
echo '</tr>';
}
?>
</table>
After fetching the query as $row variable, you need to use the following code instead
foreach($row as $tr) {
echo "<tr>";
echo "<td style=font-size:7.9px>".$tr['col1']."</td>";
echo "<td style=font-size:7.9px>".$tr['col2']."</td>";
echo "</tr>";
}
This is possible that $row only have one record fetching from database and than your for ($k=0;$k<=4;$k++) loop print that only one record 5 time
because you are using print under this loop, this loop will run 5 time.
Try the following code.
foreach($row as $val) {
echo "<tr>";
echo "<td style=font-size:7.9px>".$val['column Name']."</td>";
echo "</tr>";
}

PHP: Creating big HTML-table efficiently

I'm making a HTML table based on certain information in my MySQL database. The tables I need from the database hold the data for rows (rowid, rowname), columns (columnid, columnname) and cell data. A table, that links IDs from rows and columns together (cellid, rowid, columnid, somedata).
The table looks something like this:
__________| column1 | column2 | column3 | ...
row1 | somedata | somedata | |
----------|----------|----------|----------|-----
row2 | somedata | | somedata |
----------|----------|----------|----------|-----
... | | | |
My approach was to use several nested foreach loops, something like this:
$rows = new Rows(); //These objects are containers for objects
$columns = new Columns(); //that hold some of the database data.
$alldata = new Alldata(); //MySQL queries within these objects are irrelevant, I think. They already get the relevant data
$count = count($alldata);
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
foreach ($alldata->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) { //If the column has data the related to the row
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) { //if loop couldn't find any entries, it prints an empty cell
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
Bruteforcing, obviously this is not very efficient method when there are several hundred rows of data on any table in the database and I don't like this. Any ideas how to make this more efficient? Is there better way of creating a table like I need?
EDIT:
Pondering about this problem for a week has finally given me some answers. It was so simple!
I did a slight modification to my Column object class. Previously, my code went through all possible entries on celldata table in the database. Now Column object gets an array of celldata where columnid's match and I can do the comparison using only that data.
$rows = new Rows();
$columns = new Columns();
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
$count = count($column->getAlldata());
foreach ($column->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) {
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) {
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
Much faster, although still bruteforcing but there's less amount of data to go through. Of course, now the problem is that Column objects may do quite a lot of MySQL queries, depending on how many Columns there are.
If you ensure that the data fetched from MySQL is correctly ordered in $alldata by joining the tables and specifying an ORDER BY clause in your query:
SELECT data.*
FROM data RIGHT JOIN rows USING (rowid) RIGHT JOIN columns USING (columnid)
ORDER BY rowname, columnname;
Then you only need to output each cell in order:
echo '<table>';
echo '<thead>'
echo '<tr>';
echo '<th> </th>';
foreach ($columns->getColumns() as $column) {
echo '<th scope="col">', htmlentities($column->getColumnname()), '</th>';
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
$data = $alldata->getAlldata();
foreach ($rows->getRows() as $row) {
echo '<tr>';
echo '<th scope="row">', htmlentities($row->getRowname()), '</th>';
foreach ($columns->getColumns() as $column) {
$d = each($data);
echo '<td>', ($d ? htmlentities($d[1]->getSomedata()) : ' '), '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
The best way to solve this would be to rewrite the query for $alldata so that it is in the order you want like eggyal suggested. If you can't do that for some reason, you could iterate through $alldata in the beginning and create a properly indexed array from it. Something like this:
$ordereddata = array();
foreach($alldata as $d) {
$ordereddata[$d->getCID()][$d->getRID()] = $d->getSomedata();
}
Now you can replace your foreach($alldata) loop with this:
if(isset($ordereddata[$column->getID()][$row->getID()])) {
echo "<td>{$ordereddata[$column->getID()][$row->getID()]}</td>";
} else {
echo "<td> </td>";
}

fetching db column names only, for display in dynamic table using php

in the code below Im searching specific columns from a db table and placing them into a html table, inserting &nbsp for empty db fields to maintain uniformed structure. That part works fine, but Im having trouble figuring out the best way to go about getting the column names that are being searched and dynamically displaying them once at the very top of the html table? If my search changes, the column names displayed on the html table will change with it accordingly. Im fairly new to php/mysql and would appreciate any help guys.
$result = mysql_query('SELECT part, ers, make, model, years, oe, core, inlet, outlet FROM parts LIMIT 3');
echo '<table>';
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr>';
foreach ($row as $name => $value) {
if ( $value == "" ) $value=" ";
echo '<td> '.$value.' </td>';
}
echo '</tr>';
}
echo "</table>";
How about something like this:
$result = mysql_query('SELECT part, ers, make, model, years, oe, core, inlet, outlet FROM parts LIMIT 3');
echo '<table>';
$cnt = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($cnt == 0) {
$columns = array_keys($row);
echo '<tr><th>' . implode('</th><th>', $columns) . '</th></tr>';
}
$cnt++;
echo '<tr>';
foreach ($row as $name => $value) {
if ( $value == "" ) $value=" ";
echo '<td> '.$value.' </td>';
}
echo '</tr>';
}
echo "</table>";

php, mysql how can I produce a dynamic html with fields in the first column and data in the next colums?

I found this great example which takes an sql statement and dynamically adds the field names into a header row and the data into the following rows?
Heres the example http://www.weberdev.com/get_example-4249.html
Since HTML tables must be written out by row, you'll have to read all the data before you're able to write out your table.
$rows = array();
while ($row = mysql_fetch_assoc($result)) $rows[] = $row;
// We'll use the first row to get the field names:
foreach($rows[0] as $field => $throwaway) {
echo '<tr>';
echo '<td>' . htmlspecialchars($field) . '</td>';
// And for each field iterate through ALL rows:
foreach($rows as $row) {
echo '<td>' . htmlspecialchars($row[$field]) . '</td>';
}
echo '</tr>';
}

Categories