This question already has answers here:
MySQL query to get column names?
(22 answers)
Closed 9 years ago.
I am attempting to retrieve the column headers for html headers from a MySQL query. The structure of my application is such that the column headers aren't static (sometimes there are 4, sometimes 7, etc.) For some unbearable reason I can't find a simple way to get the column names from any given query.
My end goal is to output an html table from the query.
Well if you get the query as an associative array, you can do something like this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_assoc($results)) {
if ($i < 1) {
foreach($row as $key => $val) {
echo $key;//column name
}
}
//Do other stuff
$i++;
}
And yes, I know they should be doing mysqli_..., but this is my example using old mysql_...
Edit
To expand on this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
echo "<table>";
while ($row = mysql_fetch_assoc($results)) {
echo "<tr>";
if ($i < 1) {
foreach($row as $key => $val) {
echo "<td>".$key."</td>";//column name
}
}
echo "</tr>";
echo "<tr>";
foreach($row as $key => $val) {
echo "<td>".$val."</td>";//column name
}
echo "</tr>";
//Do other stuff
$i++;
}
You can use function mysql_list_fields for getting column names.
Code below gets data from sql. Including header column
// Data, depends on your sql statement
$sql_dt = array(); // make sure it is array
foreach( $sql_dt as $key => $val ) {
$data[] = <<< EOH
<tr>
<th>$val['column_name']</th> <tr/>
<th>$val['column_age']</th>
<tr/>
EOH;
}
$table_dt = implode( $data );
echo <<< EOT
<table>
<tr>
<th>Name</th> <tr/>
<th>Age</th>
<tr/>
{$table_dt}
<table/>
EOT;
Related
I have an SQLite database and using PHP to serve up and interact the data with.
I am trying to build an HTML table with for each SQLite table columns as the HTML Table Columns and then for each row in the SQLite table render as a for each row in the HTML table.
Issue is that each sql row data is only rendered into one html table row (with current code) (should be for each row) question would be how I go about getting the sql row data into array for looping through to render html table rows.
Currently I have;
PHP get the SQL Columns into the HTML table & SQl Row data(foreach) into HTML Table Rows (foreach)
//get table count
$countTable = $dbConnect->querySingle("SELECT COUNT(*) as count FROM ".$table['name']."");
if($countTable){
//data exists, do work
//new query to get table data
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
//init arrays
$dataColumns = array();
$dataRows = array();
while($row = $query->fetchArray(SQLITE3_ASSOC))
{
//add columns to array, checking if value exists
foreach($row as $key => $value)
{
if(in_array(''.$key.'', $dataColumns)){
//column already in array, dont add again.
}else{
//column not in array, add it.
$dataColumns[]=array(
'column'=>$key
);
}
//while in this foreach do I add the row values to an array or do it again outside this loop?
//below does not work, only adds to the one array item and renders one HTML Table row with multiple SQL Table row values
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
}
}
//build HTML table
echo '<div class="table-responsive"><table class="table"><thead><tr>';
//build columns from array... works
foreach($dataColumns as $dataColumn){
echo '<th>'.$dataColumn['column'].'</th>';
}
//close table column headers 7 start HTML table body...
echo '</tr></thead><tbody>';
//Issue is here, how do I get the each row (value is either null or not null) to
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['row_item'].'</td>';
}
echo '</tr>';
//close table body & table...
echo '</tbody></table></div>';
}else{
//table has no data
echo 'no data in the selected table';
}
I rewrote this to do it all in one loop like this.
$firstRow = true;
echo '<div class="table-responsive"><table class="table">';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
if ($firstRow) {
echo '<thead><tr>';
foreach ($row as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr></thead>';
echo '<tbody>';
$firstRow = false;
}
echo '<tr>';
foreach ($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table></div>';
You might find it clearer to read? It also avoids building an array of all the dataRows in memory.
Try to replace
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
with
$dataRows[]=$row;
Put this line at first line inside your while loop (or general outside the foreach loop over your columns), because adding a row is not connected analyzing your columns.
Then, in your output foreach, you should find the rows with all columns selected from your database query inside $dataRow (here symbolized with column1, column2, …):
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['column1'].'</td>';
echo '<td>'.$dataRow['column2'].'</td>';
echo '<td>'.$dataRow['column3'].'</td>';
echo '<td>'.$dataRow['column4'].'</td>';
echo '<td>'.$dataRow['column5'].'</td>';
echo '<td>'.$dataRow['column6'].'</td>';
echo '<td>'.$dataRow['column7'].'</td>';
// etc.
}
echo '</tr>';
After all your code should look like this (a bit simplified):
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
$dataColumns = array();
$dataRows = array();
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$dataRows[] = $row;
foreach ($row as $key => $value) {
//Bilding $dataColumns, see Question
}
}
echo '<div class="table-responsive"><table class="table"><thead><tr>';
foreach ($dataColumns as $dataColumn) {
echo '<th>'.$dataColumn['column'].'</th>';
}
echo '</tr></thead><tbody>';
echo '<tr>';
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $columnName => $columnValue) {
echo '<td>'.$columnValue.'</td>';
}
}
echo '</tr>';
echo '</tbody></table></div>';
Thanks to akrys
in the while loop, but outside the foreach column loop;
//$dataRows = array();
$dataRows[]=$row;
and in the building of the HTML Table;
foreach($dataRows as $dataRow){
echo '<tr>';
foreach($dataRow as $key => $value){echo '<td>'.$value.'</td>';}
echo '</tr>';
}
HI my code isn't working and I get this error when the code is run:
Picture of error
This is line 110 of the code:
$results = array_merge($results, $game_list[$row][$col]);
And this is the rest of the code:
$results = array();
for ($row = 0; $row < $num_rows; $row++){
if (strstr($game_list[$row][2], $search) or strstr($game_list[$row][3], $search)){
for ($col = 0; $col < count($game_list[$row]); $col ++) {
$results = array_merge($results, $game_list[$row][$col]);
$successful = true;
}
}
}
if ($successful == true){
echo "<table>
<tr>
<th>Game ID</th>
<th>Genre</th>
<th>Game Name</th>
<th>Game Description</th>
<th>Rental Cost Per Day</th>
</tr>";
// Set number of table rows
$num_rows = count($results) - 1;
// Set number of table columns
$num_cols = 5;
// Start loop to generate rows
for($row = 0; $row < $num_rows; $row++) {
// Generate row HTML
echo "<tr>";
//Start loop to generate columns (nested FOR loop!)
for($col = 0 ; $col < $num_cols; $col++) {
// Generate column HTML
echo "<td>". $results[$row][$col] ."</td>";
}
// End of columns loop
// Generate end of row HTML
echo "</tr>";
}
echo "</table>";
The code is meant to search through the array game_list and see if a keyword a user has entered is in the array. If it is, then the code will take the whole row in the array game_list and add it to the array results. This array will then be displayed in a table to the user.
If anyone can give me a fix that would be great.
The reason for that error is, that you try to merge an array with a string,
array_merge takes two arrays as arguments.
I'd suggest not to use array_merge() at all, but simply add the requested data to the results array:
<?php
$results = Array();
...
$results[] = $game_list[$row];
...
?>
I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:
$result = mysql_query("select * from table1");
while($row = mysql_fetch_array($result))
{
echo $row["field1"].','.$row["field2"];
}
In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?
I think the answer is a foreach($row as....) - but not sure where to go from there.
Yep you can do a foreach but if you just want to display your values in a CSV style you can do :
$firstRow = true;
while($row = mysql_fetch_array($result))
{
if ($firstRow) {
$firstRow = false;
$columns = array_keys($row);
// prints all the column names
echo implode(',', $columns);
}
// print all the values
echo implode(',', $row);
}
If you want more control over what you output you can use a foreach :
while($row = mysql_fetch_array($result))
{
foreach ($row as $column => $value) {
echo $column.' : '.$value."\n";
}
}
You'll want to count the $row array
while($row = mysql_fetch_array($result))
{
$columns = count($row);
for($i = 0; $i < $columns; $i++)
{
echo $row[$i].',';
}
}
Or you can use foreach() as #Dagon has pointed out -
while($row = mysql_fetch_array($result))
{
foreach($row as $column)
{
echo $column . ',';
{
}
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.
this is the values in the $result
id name
1 a
2 b
2 c
2 d
3 e
..
I'm creating a loop function using mysql_fetch_array()
while($row = mysql_fetch_array($result)) {
$temp_id = $row['id'];
while($temp_id == $row['id']) {
if($temp_id == $row['id']) {
mysql_fetch_array($result);
}
$temp_id = $row['id'];
echo $row['name'].",";
}
echo "<br/>";
}
this works but the problem is, the mysql_fetch_array jumps on one of the values during the transition of the id's..
I want the values of this to be like these
a
b,c,d
e
my question is, is there a simple rewind function that will step only once in the rows?
I have searched about the mysql_data_seek() but I think this would require additional control variables like $i to locate the address..
thanks.. any suggestions and function samples will be very great!
Use one loop with mysql_fetch_array first to create an array of the rows. Then, iterate over the rows themselves.
Based on the update to your question it seems like you would want to use GROUP_CONCAT in the query, but you can still do it in PHP:
$rows = array();
while($row = mysql_fetch_assoc($result)) {
if (!isset($rows[$row['id']]) {
$rows[$row['id'] = array();
}
$rows[$row['id']][] = $row['name'];
}
foreach ($rows as $row) {
echo implode(',', $row) . "<br>";
}
Try this code
while($row = mysql_fetch_array($result)) {
$temp[$row['id']][] = $row['name'];
}
foreach($temp as $row) {
echo implode(',', $row) . '<br/>';
}
<?php
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
$arrayResult = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
for ($x = 1; $x <= $num_rows; $x++){ //1st for loop
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
?>
$columns is an array entered by the user eg: $columns = array ('Column1', 'Column2', 'Column3);. These are the names of the columns which are in a given $table.
My idea was to create a function that displays the data from the MySQL table with the info from the $columns array. The problem is in the second for loop. The value of $i is reset every time the first loop is done, so I get the same result over and over again (the number of rows in the table).
My question is this: How do I keep the $i in the second loop from resetting?
Thank you in advance.
The reason you get the same result over and over is not because $i, but $arrayResult.
The right way is like this:
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while ($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
In your code you simple fetch always the first row and regardless of the subsequent cycles you only deal with that first row.
Just place
$arrayResult = mysql_fetch_array($result);
within the first loop just before echo '<tr>';
Anyway, for is not the best choice for iterating the records of a table, consider using while.
Why Dont you use while loop? If you use while you even don't need mysql_num_rows($result). Try this
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
I m sure, you will get your ans
Your code won't work ever. Because you didn't read manual entry for mysql_fetch_array()
There is no use for the for loops these days. You need some manual to see how to deal with loops in PHP. foreach and while you will need more often than for.
The idea of creating such a function is wrong. combining SQL and HTML in one function is a sign of VERY BAD design. What you really need is a function to get SQL data into array and a template.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$data = sqlArr("SELECT * FROM table");
include 'template.php';
a template
<table border='1'>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $col): ?>
<td><?=$col?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
However, you can put this latter template code into function, if you're gonna use it often.
and call it like
<? drawTable($data) ?>