Show values from DB in specifc HTML table cell - php

I am trying to get a table view from DB values in a specific pattern.
It should look like this:
Plan View
In the DB I have added row/col values to assign the "cell names" to a specific cell:
DB table
Using this code:
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
$data = $pdo->query("SELECT row, col, number FROM stalls ORDER BY row ASC, col ASC")->fetchAll();
echo'<table style="width:100%;">';
foreach ($data as $entry)
{
if($entry['row'] > 0)
{
for($r=0;$r<=$maxrow;$r++)
{
if($r == $entry['row'])
{
echo '<tr style="border: 1px solid black;">';
for($c=1;$c<=$maxcol;$c++)
{
if($c == $entry['col'])
{
echo '<td style="border: 1px solid black;">row: '. $r . ' - col: ' . $c . ' - value: ' . $entry['number'] .'</td>';
}
else
{
echo '<td style="border: 1px solid black;"></td>';
}
}
echo '</tr>';
}
}
}
}
echo '</table>';
I can only get this view:
Shifted rows
How would I get the values of "row 1" to be shown in row 1, without the "shift"?
Thank you very much for your help!

You could try something like - note this is untested code:
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
$oldRow = 0; // init row counter
$arr = array_fill( 0, $maxcol, " " );
$tmp = "";
echo'<table style="width:100%;">';
foreach ($data as $entry) {
// get the data
$row = $entry['row'];
$col = $entry['col'];
$nbr = $entry['number'];
// is the row number different and not the first entry
if( $oldRow != $entry['row'] && $oldRow != 0 ) {
//--- convert to html type string
$tmp = implode( "</td><td>", $arr );
//--- show html
echo'<tr><td>".$tmp."</td></tr>";
//--- reset temp values
$arr = array_fill( 0, $maxcol, " " );
$oldRow = $entry['row']; // set new row number
}
$arr[$row][$col] = $nbr;
}
//--- convert to html type string for last entry processed
$tmp = implode( "</td><td>", $arr );
//--- show html
echo'<tr><td>".$tmp."</td></tr>";
echo "</table>";

Finally, not very nice, but it works for me...
// get max rows
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
// get max cols
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
// get rows and number of cols in row
$rowmeta = $pdo->query("SELECT row, COUNT(*) as count FROM stalls WHERE row <> 0 GROUP BY row ORDER BY row ASC")->fetchAll(PDO::FETCH_ASSOC);
// get rest of stuff
$data = $pdo->query("SELECT row, col, number FROM stalls ORDER BY row ASC, col ASC")->fetchAll(PDO::FETCH_ASSOC);
echo'<table style="table-layout: fixed; width:100%;">';
// iterate trough rows from meta
foreach($rowmeta as $rowmeta_row)
{
echo '<tr style="width: calc(100%/'.$maxcol.');border: 1px solid black;">';
// get data part
foreach($data as $d)
{
// check if we're still in same row as data
if($rowmeta_row["row"] == $d['row'])
{
// move left trough cols
for($c=1;$c<=$maxcol;$c++)
{
// check if we're in the right col and it is not an isle
if($c == $d['col'] && $d['number'] != 'isle')
{
echo '<td style="border: 1px solid black;">row: '. $d['row'] . ' - col: ' . $d['col'] . ' - value: ' . $d['number'] .'</td>';
}
// still in right col, but isle
if($c == $d['col'] && $d['number'] == 'isle')
{
echo '<td style="border: 1px solid black;">leer</td>';
}
}
}
}
echo '</tr>';
}

Related

MySQL PHP Query in CI

I need help with this. I must pass a PHP MySQL function to CodeIgniter, but it does not show me the data, it stops right in if(array_key_exists($pos, $rs))
Does the query well but does not enter the conditional if
Any solution?
This is my Code in CodeIgniter
public function table($hour, $row)
{
global $rs;
if ($rs === null)
{
$this->db->select("CONCAT(t.tbl_row, '_', t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name", false);
$this->db->join('redips_timetable AS t', 't.sub_id = s.sub_id');
$rs = $this->db->get('redips_subject AS s')->result();
}
echo '<tr>';
echo '<td class="mark dark">' . $hour . '</td>';
for ($col = 1; $col <= 5; $col++)
{
echo '<td>';
$pos = $row . '_' . $col;
if(array_key_exists($pos, $rs))
{
$elements = $rs[$pos];
$id = $elements['sub_id'] . 'b' . $elements['tbl_id'];
$name = $elements['sub_name'];
$class = substr($id, 0, 2);
echo "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
echo '</td>';
}
echo "</tr>\n";
}
Original MySQL code
function table($hour, $row) {
global $rs;
// if $rs is null then query database (this should be executed only once - first time)
if ($rs === null)
{
// first column of the query is used as key in returned array
$rs = sqlQuery("select concat(t.tbl_row,'_',t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name
from redips_timetable t, redips_subject s
where t.sub_id = s.sub_id", 0);
}
print '<tr>';
print '<td class="mark dark">' . $hour . '</td>';
// column loop starts from 1 because column 0 is for hours
for ($col = 1; $col <= 5; $col++) {
// create table cell
print '<td>';
// prepare position key in the same way as the array key looks
$pos = $row . '_' . $col;
// if content for the current table cell exists
if (array_key_exists($pos, $rs)) {
// prepare elements for defined position (it can be more than one element per table cell)
$elements = $rs[$pos];
// id of DIV element will start with sub_id and followed with 'b' (because cloned elements on the page have 'c') and with tbl_id
// this way content from the database will not be in collision with new content dragged from the left table and each id stays unique
$id = $elements[2] . 'b' . $elements[1];
$name = $elements[3];
$class = substr($id, 0, 2); // class name is only first 2 letters from ID
print "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
// close table cell
print '</td>';
}
print "</tr>\n";
}
/*
if you need find array key
you got object in $rs varible
( $rs = $this->db->get('redips_subject AS s')->result(); )
so need convert obj to array in for each loop
*/
public function table($hour, $row)
{
global $rs;
if ($rs === null)
{
$this->db->select("CONCAT(t.tbl_row, '_', t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name", false);
$this->db->join('redips_timetable AS t', 't.sub_id = s.sub_id');
$rs = $this->db->get('redips_subject AS s')->result();
}
echo '<tr>';
echo '<td class="mark dark">' . $hour . '</td>';
for ($col = 1; $col <= 5; $col++)
{
$arr = get_object_vars($rs[$col]);
echo '<td>';
$pos = $row . '_' . $col;
if(array_key_exists($pos, $arr))
{
$elements = $arr[$pos];
$id = $elements['sub_id'] . 'b' . $elements['tbl_id'];
$name = $elements['sub_name'];
$class = substr($id, 0, 2);
echo "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
echo '</td>';
}
echo "</tr>\n";
}

How to get a html-table from an sql-query with various numbers of columns?

I have a html-form to read out data from an SQL-database. The number of selections is completely free, which means that there are no obligatory fields.
I would like to show the results that meet all selected criteria in a html-table. Here is my code:
<?php
include("../files/zugriff.inc.php");
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$datenWerte = array();
$fruitname = $_POST["fruitname"];
$fruitgroup = $_POST["fruitgroup"];
$vegetablegroup = $_POST["vegetablegroup"];
$country = $_POST["country"];
$season = $_POST["season"];
$diameter = $_POST["diameter"];
$color = $_POST["color"];
if(!empty($fruitgroup)) {
$datenWerte['fruitgroup'] = $fruitgroup;
}
if(!empty($vegetablegroup)) {
$datenWerte['vegetablegroup'] = $vegetablegroup;
}
if(!empty($country)) {
$datenWerte['country'] = $country;
}
if(!empty($season)) {
$datenWerte['season'] = $season;
}
if(!empty($diameter)) {
$datenWerte['diameter'] = $diameter;
}
if(!empty($color)) {
$datenWerte['color '] = $color;
}
foreach ($datenWerte as $key => $value) {
$spalten[] = $key;
$werte[] = "'$value'";
}
echo "<b>Results:</b><br><br>";
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql);
$data = array();
while($row = $result->fetch_object()){
$data[] = $row;
}
// Numeric array with data that will be displayed in HTML table
$aray = $data;
$nr_elm = count($aray); // gets number of elements in $aray
// Create the beginning of HTML table, and of the first row
$html_table = '<table border="1 cellspacing="0" cellpadding="2""><tr>';
$nr_col = count($spalten); // Sets the number of columns
// If the array has elements
if ($nr_elm > 0) {
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++) {
$html_table .= '<td>' .$aray[$i]. '</td>'; // adds the value in
column in table
// If the number of columns is completed for a row (rest of
division of ($i + 1) to $nr_col is 0)
// Closes the current row, and begins another row
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $html_table .= '</tr><tr>'; }
}
// Adds empty column if the current row is not completed
if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col -
$col_to_add). '"> </td>';
}
$html_table .= '</tr></table>'; // ends the last row, and the table
// Delete posible empty row (<tr></tr>) which cand be created after last
column
$html_table = str_replace('<tr></tr>', '', $html_table);
echo $html_table; // display the HTML table
}
mysqli_close($db);
?>
Unfortunately, it´s not working. Could somebody please help me to find the error?
Than you very much in advance!

How can I print out <tr> after every 4 mysql entries in my while loop?

$q2 = mysql_query("SELECT * FROM artwork LEFT JOIN folder ON folder.folder_id=artwork.folder_id WHERE id IN(0".$userids.")");
while($row = mysql_fetch_array($q2)){
$link .= '<td align="center"><a href="/art/'.$row['id'].'" title="'.$row['name'].'">
<img src="/img/artwork/'.$row['folder'].'/'.$row['file'].'" height="80" /></a><br />
<span align="center">[remove] [view]</span></td>';
}
link is getting echo'd out with one td, but I need to make it so after every 4 mysql entries it adds a tr
Just maintain a counter and test if it is divisible by 4:
$counter = 0;
while ($row = mysql_fetch_array($q2)) {
if ($counter%4 === 0) $link .= "<tr>";
$link .= "<td>...</td>";
if ($counter%4 === 3) $link .= "</tr>";
$counter++;
}
Define a variable to count td's and check if it's rminder by 4 is 0 then open an close tr
$item = 0;
while ($row = mysql_fetch_array($q2)) {
if ($item % 4 == 0) $link .= "<tr>";
$link .= "<td>...</td>";
if ($item % 4 == 0) $link .= "</tr>";
$item++;
}
if($item % 4 != 0){//IF COUNT OF TD IN LAST ROW IS LESS THAN 4
while($item % 4 != 0){
$link.= "<td></td>";
$item++;
}
$link.= "</tr>";
}

Extract a range of rows from CSV file using PHP

I'm very new to PHP and have been experimenting with combining with css to turn a CSV file into a table on my site. I wondered if you could select to show just a range of rows from a CSV file, e.g. rows 5 to 20, and found the code below to show certain columns.
Is there a simple way to switch this to show selected rows instead?
<?php
$row = 1;
if (($handle = fopen("donors.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<td style="border-top: 1px solid rgb(111,180,224); border-left: 1px solid rgb(111,180,224); border-bottom: 1px solid rgb(111,180,224);" align="left" bgcolor="#0066cc" height="36" valign="middle" ><b><font color="#ffffff" size="2"> '.$value.' </font></b></td>';
}else{
echo '<td style=" border-bottom: 1px solid rgb(111,180,224);" sdval="9" sdnum="1040;" align="left" bgcolor="#ffffff" height="25" valign="middle"><font color="#000000" size="2"> '.$value.' </font></td>';
}
}
if ($row == 1) {
echo '</tr>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
echo '</center>';
fclose($handle);
}
?>
I'm not really sure to undestand what you want to display.
But on the test website i added a table which diplay a range of lines.
Here is the code of this table:
echo "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>
<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\">";
$file = '/var/www/test/test.csv';
echo "<h1><b>Lines X to Y</b></h1>";
echo "<table>"; //create the html table
$x=2; //define the first line to display
$y=4; //define the last line to display
$line_counter=0;
foreach ($lines as $line) { //loop to fill your table with csv data
if($x<=$line_counter && $line_counter<=$y)
{
$expl = explode(",", $line); //explode each line on "," to create the rows
echo "<tr>"; //create each line of your table
$c=0;
while ($c<=26) { //loop to extract rows 5 to 20
if(($c % 2) == 1){ //odd rows
echo "<td class=\"odd\">".$expl[$c]."</td>";
}
elseif(($c == 0)){
echo "<td class=\"even\">".$expl[$c]."</td>";
}
else{
echo "<td class=\"even\">".$expl[$c]."</td>"; //even rows
}
$c++;
}
echo "</tr>";
$x++;
}
$line_counter++;
}
echo "</table>";
echo "<h1><b>content of the file</b></h1>";
foreach ($lines as $line) { //loop to fill your table with csv data
echo "$line<br/>" ;
}
The CSS is always in a separate file, and is the same as my first answer.
Select a range of rows:
i adapted this code from an old project, but it should work.
<?php
echo "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>
<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\">";
$file = '/volume1/web/Print data.csv';
$lines = file($file);
if (file_exists($file)){
//echo "$file exists<br/>";
echo "<table>"; //create the html table
foreach ($lines as $line) { //loop to fill your table with csv data
$expl = explode(",", $line); //explode each line on "," to create the rows
echo "<tr>"; //create each line of your table
$c=5;
while ($c<=20) { //loop to extract rows 5 to 20
if(($c % 2) == 1){ //odd rows
echo "<td class=\"odd\">".$expl[$c]."</td>";
}
else{
echo "<td class=\"even\">".$expl[$c]."</td>"; //even rows
}
$c++;
}
echo "</tr>";
}
echo "</table>";
}
else{
echo "file is not here: $file";
}
?>
For the css:
you should use an external .cssfile with this code
.odd {
border-top: 1px solid rgb(111, 180, 224);
border-left: 1px solid rgb(111, 180, 224);
border-bottom: 1px solid rgb(111, 180, 224);
background:#0066cc;
color:white;
font-weight:bold;
font-size:12px;
}
.even {
border-bottom: 1px solid rgb(111, 180, 224);
background: #ffffff;
color:#000000;
font-size:12px;
}
To check this css you can see this jsfiddle
I hope it will help you.
Edit
Fixed some missing ;. Added an picture of the result
1) Fetch your CSV file to an array with the below function (source: jaywilliams # GIST)
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
2) Iterate over the desired range of rows
$data = csv_to_array($file,$delimiter);
echo "your table header stuff"; //<table> ...
//first row numbered as 1
$from_row = 2; //second
$to_row = 50;
//first row numbered as 0
for($i = from_row-1; $i< $to_row-1; $i++)
{
echo "<tr>"; //start row
//now, every row of the CSV file is an array and consists of fileds=>values
//so now you are dealing with columns
foreach($data[$i] as $key=>$value
{
echo "<td>" . $value . "</td>";
}
echo "</tr>"; //end row
}
echo "your table footer stuff"; //</table> ...
From here, I guess you can do whatever your want, using CSS to style the tables. What is important, if you want the table header, you can feed the function with a CSV file with col names saved in first row.

Not printing all rows in mysql table

I'm creating a movie database for private purposes. As a part of the database I want to be able to show the movies by sorting by genre, starting letter of movies or just show all.
I want to display the hits in a three column table until all rows in the database table have been printed.
For example:
Ice age 1 Ice age 2 Ice age 3
Die Hard 1 Die Hard 2 Die hard 3
What happens with the code below (Which is used when all movies should be shown) is that it stops after 39 rows even though I know it's 50 rows, mysql_num_rows() returns 50 and when I just printed the complete db table in 1 column I got 50 rows.
$counterone = 0;
$countertwo = 0;
if ($_movietype == 'showmeeverything')
{
$movieresult = mysql_query("SELECT url,title FROM movies ORDER BY title");
if(mysql_num_rows($movieresult) == 0)
{
nomovie();
}
echo '<p align="center">Go back</p>';
echo '<table border="1" cellspacing="2" cellpadding=2" align="center">';
echo '<tr><td colspan="3" align="center"><b>Title</b></td></tr>';
echo mysql_num_rows($movieresult);
while ($counterone < mysql_num_rows($movieresult))
{
$counterone++;
echo '<tr>';
while (($result = mysql_fetch_array($movieresult)) && $countertwo < 3)
{
echo '<td>';
echo '' . $result['title'] . '';
echo '</td>';
$countertwo++;
}
echo '</tr>';
$countertwo = 0;
}
echo '</table>';
echo '<p align="center"><a align="center" href="index.php">Go back</a></p>';
}
You're not incrementing $counterone in the right spot. You're counting table ROWS, but are working off number of records. $counterone should be inside the internal while($result) loop. And once it's there, $countertwo is redundant.
Try this instead:
$counter = 0;
while($row = mysql_fetch_array($movieresult)) {
if ($counter % 3 == 0)
echo '<tr>';
}
echo "<td> blah blah blah </td>";
if ($counter % 3 == 2) {
echo '</tr>';
}
$counter++;
}
Try this:
$counterone = 0;
$countertwo = 0;
if ($_movietype == 'showmeeverything')
{
$movieresult = mysql_query("SELECT url,title FROM movies ORDER BY title");
if(mysql_num_rows($movieresult) == 0)
{
nomovie();
}
echo '<p align="center">Go back</p>';
echo '<table border="1" cellspacing="2" cellpadding=2" align="center">';
echo '<tr><td colspan="3" align="center"><b>Title</b></td></tr>';
echo mysql_num_rows($movieresult);
$numrows = mysql_num_rows($movieresult);
while ($counterone < $numrows)
{
$counterone++;
echo '<tr>';
while (($result = mysql_fetch_array($movieresult)) && $countertwo < 3)
{
echo '<td>';
echo '' . $result['title'] . '';
echo '</td>';
$countertwo++;
}
echo '</tr>';
$countertwo = 0;
}
echo '</table>';
echo '<p align="center"><a align="center" href="index.php">Go back</a></p>';
}

Categories