First let me start by saying this is a homework problem so the way I have to build this table is because of the requirements for the assignment. The requirements call for three php functions to build an html table. I have a table, td, and tr function. I think I am very close to figuring out hwo to get this to work. Just running into one small problem and was wondering if someone could help me out or explain why I am running into this problem. Here is my code:
<?php
//need a constant to keep track of the number of rows
define('NUM_ROWS', '3');
//function to start building table
function table()
{
$myTable = '<table border="1">' . tr($myTable) . '</table>';
return $myTable;
}
//function to build table rows
function tr( $myTable )
{
$myTable .= '<tr>' . td($myTable) . '</tr>';
return $myTable;
}
//function to build table data
function td($myTable)
{
$rowData = array("Planes", "Trains", "Automobiles");
for($i = 0, $length = count($rowData); $i < $length; $i++)
{
$myTable .= '<td>' . $rowData[$i] . '</td>';
}
return $myTable;
}
echo table();
?>
The problem I am having is in the table function. If I write the function the way it is shown above it will display the table but it also gives me an undefined variable error on $myTable when I call the tr function. If I change that function to look like the function below it doesn't display my table at all and just shows a blank page.
function table()
{
$myTable = '<table border="1">';
tr($myTable);
$myTable .= '</table>';
return $myTable;
}
Any ideas on what I am doing wrong or can do differently?
You are not actually using the passed variable nicely anyways so just don't try to pass the variable (which you were passing before it existed and hence was complaining about being undefined); just do this:
<?php
//need a constant to keep track of the number of rows
define('NUM_ROWS', '3');
//function to start building table
function table()
{
$myTable = '<table border="1">' . tr() . '</table>';
return $myTable;
}
//function to build table rows
function tr()
{
$tr = '<tr>' . td() . '</tr>';
return $tr;
}
//function to build table data
function td()
{
$td = '';
$rowData = array("Planes", "Trains", "Automobiles");
for($i = 0, $length = count($rowData); $i < $length; $i++)
{
$td .= '<td>' . $rowData[$i] . '</td>';
}
return $td;
}
echo table();
?>
you need to pass
you aren't passing any parameter to function table
function table($myTable)
{
$myTable = '<table border="1">' . tr($myTable) . '</table>';
return $myTable;
}
Try this.
//need a constant to keep track of the number of rows
define('NUM_ROWS', '3');
//function to start building table
function table($val)
{
$myTable="";
$myTable = '<table border="1">' . tr($val) . '</table>';
return $myTable;
}
//function to build table rows
function tr( $val )
{
$myTable="";
$myTable .= '<tr>' . td($val) . '</tr>';
return $myTable;
}
//function to build table data
function td($val)
{
$myTable="";
for($i = 0, $length = NUM_ROWS; $i < $length; $i++)
{
$myTable .= '<td>' . $val[$i] . '</td>';
}
return $myTable;
}
$rowData = array("Planes", "Trains", "Automobiles");
echo table($rowData);
Related
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";
}
So I am trying to make a multiplication table and have run into this issue :
<?php
$table = '';
if ($_POST) {
$table .= '<table border="1">';
for ($i = 0; $i < $_POST['qty_line']; $i++) {
$table .= '<tr>';
for ($j = 0; $j < $_POST['qty_column']; $j++) {
$val = $i * $j;
$table .= '<td width="50"> VARIABLE GOES HERE </td>';
}
$table .= '</tr>';
}
$table .= '</table>';
}
?>
Sorry if this is a very simple question but I can't find a solution after searching. Basically i want to insert the $val variable into where it says "VARIABLE GOES HERE" on that specific table data cell. How would I go about this?
You could use
$table .= '<td width="50">' . $val . '</td>';
See the documentation for more examples.
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!
I'm trying to display all the information in a msSQL table in an HTML table and have up with something that is not so great.
<table border="1">
<?
echo "<tr>";
for ($i = 0; $i < mssql_num_fields($result); ++$i){
echo "<th>" .$column_names[$i] . "</th>";
}
echo "</tr>";
$num_rows = mssql_num_rows($result);
for ($i = 0; $i < $num_rows; ++$i){
echo "<tr>";
foreach ($column_names as $key => $val){
$result_row = mssql_query("SELECT * FROM username WHERE id = '$i'");
$row = mssql_fetch_assoc($result_row);
echo "<td>";
echo $row[$val];
echo "</td>";
}
echo "</td>";
}
?>
</table>
This works. The first part prints out the column names successfully, but as for the rest:
1) I think it is sort of cumbersome to make a query for every time through the loop
2) it doesn't really work because the ids of the rows go much higher than the number of rows in the table, as some ids aren't used.
It seems like I should be able just make one query and pull everything from the database at one go, then build my HTML table from that, but I can't figure out how to access it row by row where I could go $row[next row][shifted value from $column_names. How can improve this query?
function table_cell($item, $header=false) {
if (!$item) return '';
$elemname = ($header) ? 'th' : 'td';
$escitem = htmlspecialchars($item, ENT_NOQUOTES, 'UTF-8');
return "<{$elemname}>{$escitem}</{$elemname}>";
}
function table_header_cell($item) {
return table_cell($item, true);
}
function table_row($items, $header=false) {
$func = ($header) ? 'table_header_cell' : 'table_cell';
return "<tr>\n\t".implode("\n\t", array_map($func, $items))."\n</tr>\n";
}
function echo_result_as_table($result) {
if ($result && $row = mssql_fetch_assoc($result)) {
$columnnames = array_keys($row);
echo "<table>\n", table_row($columnnames, true), "\n";
do {
echo table_row($row), "\n";
} while ($row = mssql_fetch_assoc($result));
echo "</table>\n";
}
}
$result = mssql_query("SELECT * FROM username");
echo_result_as_table($result);
if ($result) mssql_free_result($result);
If you have an array of associative arrays instead of a raw mssql result handle, you can use a function like this to produce a table string:
function array_to_table($arrayofassoc) {
if (!$arrayofassoc) return '';
$tablestr = '<table>';
$tablestr .= table_row(array_keys($arrayofassoc[0]), true);
$tablestr .= implode('', array_map('table_row', $arrayofassoc));
$tablestr .= '</table>';
return $tablestr;
}
try this:
while($row = mysql_fetch_results($result)){
echo '<td>'.$row['column_name'].'</td>';
}
with 'column_name' being the name of the column in mysql.
but some will say..."wait, but PDO"
I wonder how can i find out last in table with PHP, aka if that is last then i want to apply different style and content to it.
This is part of my code generating table content.
$content .= '</tr>';
$totalcols = count ($columns);
if (is_array ($tabledata))
{
foreach ($tabledata as $tablevalues)
{
if ($tablevalues[0] == 'dividingline')
{
$content .= '<tr><td colspan="' . $totalcols . '" style="background-color:#efefef;"><div align="left"><b>' . $tablevalues[1] . '</b></div></td></tr>';
continue;
}
else
{
$content .= '<tr>';
foreach ($tablevalues as $tablevalue)
{
$content .= '<td>' . $tablevalue . '</td>';
}
$content .= '</tr>';
continue;
}
}
}
else
{
$content .= '<tr><td align="center" style="border-bottom: none;" colspan="' . $totalcols . '">No Records Found</td></tr>';
}
I know there is option to do something like that with jQuery later on, but I don't want to complicate it and just solve it with php at time when i generate table.
Keep a count:
$count = 1;
foreach ($tablevalues as $tablevalue)
{
$count++;
if( $count > count( $tablevalues)) {
echo "Last td tag is up next! ";
}
$content .= '<td>' . $tablevalue . '</td>';
}
you can execute any code in last loop:
for($i=0;$i<count($tablevalues);$i++)
{
$tablevalue=$tablevalues[$i];
$content .= '<td>' . $tablevalue . '</td>';
if($i==count($tablevalues)-1){
// last loop execution
}
}
here is a somehow trick
foreach ($tablevalues as $k => $tablevalue)
{
if ($k==count($tablevalues)-1)
{
// last td of current row
$content .= '<td>' . $tablevalue . '</td>';
}
else
{
$content .= '<td>' . $tablevalue . '</td>';
}
}
I just hope that your keys of your $tablevalues set match this code.
You should use a for($i = 0; i < count($tablevalues); $i++) {} loop and consider count($tablevalues)-1 to be the last key of your array.
So that $tablevalues[count($tablevalues)-1] is your last <td>.
Why dont you use jQuery?It has provisions to do something like that.