creating html table from data pulled from database using PHP - php

I am working on a project to pull data from a sql database via PHP and create an HTML table from it. It is part of a form I am creating and the table will be a listing of what I am selling, costs, weights, etc. Anyway, I need to do this with PHP. So far I have the following in this section of my code to make this table:
<?php
$db=mysqli_connect(null,null,null,'weblab')
or die("Can't connect to DB: " .
mysqli_connect_error());
$query="SELECT fruit_item_no, fruit_name, fruit_price, fruit_weight FROM fruit_$
$result=mysqli_query($db, $query);
if (!$result) {
print "Error - The query could not be executed!" .
mysqli_error();
}
print "<table class = 'main'><caption> <h2> Fruit Purchasing Form </h2> </c$
print "<tr align = 'center'>";
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
}
else {
print "There were no such rows in the table <br />";
}
print "</table>";
?>
The problem I am running into is when I attempt the view the entire page in Chrome, all I see is:
I think the error is somewhere around this section of code:
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
If anyone can give me a little direction on what I might be missing, I would greatly appreciate it. I have been researching a while now and no clear fix has come up that i can see.
UPDATE:
Thought it would be best to just update my post instead of new question or comment somewhere. Thanks to all your suggestions I was able to correct my code to properly display my table and worked out all validation errors. I apologize for the code reading nightmare... I am still fairly new at this and I need to work more at it.
I did run into one issue I still cannot resolve though. I am trying to add an input box on the end of each row in the table I created. Problem is no matter what I try the boxes stay in a line above the table (pretty much at the top of the browser screen.
I placed this line in the sql query block to try to get the input box:
echo ("<input name='item[]' type='text' .=''/>");
and I also tried:
echo ("<input type='text' name ='item'/>");
Both did the same thing in giving me the line of boxes along the top. Any direction you could provide in getting these to be at the end of each row? I do not need it to put data back in the database or add to a table there. I just am trying to get input fields that will allow input that will submit with my form.

You can simplify the code by running and while loop on the result and iterating through the rows. And then using foreach loops since each row is an array of key value pairs. On the first iteration you could print the header.
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$i = 0;
// loop through each row in the result
while ($row=mysqli_fetch_assoc($result)) {
// if first then print the header
if ($i == 0) {
print "<tr>";
foreach ($row as $field => $value) {
print "<th class='a'>".$field."</th>";
}
print "</tr>";
}
// print the row
print "<tr>";
foreach ($row as $value) {
print "<td class='b'>".$value."</td>";
}
print "</tr>";
$i++;
}
}
else {
print "<tr></td>There were no such rows in the table</td></tr>";
}
As suggested in the comments it would be a good idea to separate your view from your code.

In your second for loop, you have this:
for($index=0; $index<$num_fields; $row_num++)
Well, the value of $index will remain 0 throughput your execution. Try changing it to
for($index=0; $index<$num_fields; $index++)
{
$row_num++;
//rest of code
}
Hope it helps.

This is unnecessarily complicated:
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
Something like this would be easier to read and should solve your problem, which was caused by incrementing the wrong index on one of the for loops:
$headers = false;
while($row=mysqli_fetch_assoc($result)) {
if (!$headers) {
echo "<thead><tr>";
foreach($row as $k=>$v) {
echo "<th>$k</th>";
}
echo "</tr></thead>";
$headers = true;
}
echo "<tr>";
foreach ($row as $k=>$v) {
$v=htmlspecialchars($v);
print "<td class='b'>$v</td>";
}
echo "</tr>";
}
But I would strongly recommend a) using a database abstraction layer like PDO, and b) separating your logic from your presentation. Debugging problems with HTML is made 100 times harder when it's jumbled all together with your PHP like this.

Related

a PHP table map

I want to create a game where I have to create a map with PHP. I want to create 100 tables boxes in the right way but I can't get it work...
$field = 100;
echo "<table border='3px' dir='ltr'>";
for ($row=0; $row < 10 ; $row++) {
echo "<tr>";
for ($column=0; $column < 10; $column++) {
echo "<td>";
echo $field;
$field--;
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This gives me this table:
But I will need a table like:
If a for loop is not a requirement.
I would use an array, then you have a set to work from rather then calculating things, then you just need reverse the odd row, like so:
$rows = array_reverse(array_chunk(range(1, 100), 10));
echo "<table>\n";
foreach ($rows as $level => $row) {
if (($level-1) % 2) {
$row = array_reverse($row);
}
echo "\t<tr>\n";
foreach ($row as $value) {
echo "\t\t<td>$value</td>\n";
}
echo "\t</tr>\n";
}
echo "<table>\n";
https://3v4l.org/204eh

DO while based on query result

I got a block of the code written in PHP it uses a DB connection to an Oracle DB, i need to run a query on a data and the result for the first query it should be an input of the next query and this should be inside a loop, if i don't got any more result from the next query i should exit the loop, at the moment i am using and integer to loop through max 5 times as i know this the maximum possible results received, but this is dynamic.
My actual code what is working is the following:
this is the form when i input the data
<form name="identificare_cusut" action="test_hlkz.php" method="post">
Scanati piesa: <input type="text" name="piesa"><br>
<input type="submit" value="Cautare">
</form>
php code where i verify data and use function to execute query on DB while i am running a loop.
if (isset($_POST['piesa']) && strlen($_POST['piesa'])>0) {
$barcode = $_POST['piesa'];
}
if (isset($barcode)) {
echo "<tr>";
echo "<th>".$barcode."</th>";
echo "</tr>";
array_push($trasabilitate_array, $barcode);
$x=1;
do {
$arr=get_query_results_hlkz($barcode);
if ($arr) {
foreach ($arr as $row) {
echo "<tr>";
echo "<th>" .$row[0]. "</th>";
echo "</tr>";
$barcode=$row[0];
array_push($trasabilitate_array, $row[0]);
}
}
$x++;
} while ($x <=5);
}
i don't want to use a static solution like while ($x <=5)
Any idea how to fulfill this in a different way?
Should do the trick. So if the next $arr is empty it will exit the loop.
<?php
if (isset($_POST['piesa']) && strlen($_POST['piesa'])>0) {
$barcode = $_POST['piesa'];
}
if (isset($barcode)) {
echo "<tr>";
echo "<th>".$barcode."</th>";
echo "</tr>";
array_push($trasabilitate_array, $barcode);
$x=1;
do {
$arr=get_query_results_hlkz($barcode);
if ($arr != null) {
foreach ($arr as $row) {
if ($arr == null) {
$x = 6;
}
if($x < 6){
echo "<tr>";
echo "<th>" .$row[0]. "</th>";
echo "</tr>";
$barcode=$row[0];
array_push($trasabilitate_array, $row[0]);
}
}
$x++;
}
} while ($x <=5);
}
?>

How to get id while in a loop in php

Wanted to get 2 values id and name but im confuse how get it, i wanted to show the id in the link. heres the sample code.
echo "<table width=\"100%\" border=\"1\" cellpadding=\"5\" cellspacing=\"2\" bordercolor=\"#FFFFFF\">";
$count = 1;
$id=$_GET['id'];
$col1 = $col2 = array();
$rowcount = round(mysqli_num_rows($nquery) / 2);
while($crow = mysqli_fetch_assoc($nquery)) {
if($count > $rowcount) $col2[] = $crow['title'];
else $col1[] = $crow['title'];
$count++;
}
$counter = 0; // Arrays start with 0
foreach($col1 as $crow) { // $col1 will always be >= $col2
$row2 = (isset($col2[$counter])) ? $col2[$counter] : "";
echo "<tr><td><a href='index.php?page=".$id."'>" . $crow . "</td><td>" . $row2 . "</td></tr>";
$counter++;
}
echo "</table>";
?>`
id wont show up on the link. Hope someone can help. Thanks
You're trying to get $id values from the query string (that's what the $_GET superglobal is) and not from the database.
If both elements (ID and name) are coming from the same database query, you may try something like this:
$crow = mysqli_fetch_assoc($nquery);
foreach ($crow as $row)
{
echo $row['id'].' is the ID and '.$row['title'].' is the title';
}
if you remain within the foreach loop, you can use $row['id'] and $row['title'] to build the table element and link you're trying to obtain.

Display data with odds and evens

I've checked around google and in here and I am unable to find an answer specific to what I'm wanting to do.
Basically, I am trying to make a table with the database like this:
[0001][0002]
[0003][0004]
However, for some reason I am unable to do that.
This is what I've got down, and it's not even functioning. I would like to note that I am pretty new to php, although that may be obvious.
<table>
<?php
...
$x = 0;
while($info = mysql_fetch_array( $data ))
{
while($info['id'] <= 4)
{
if($x ==0){ // [I feel like the error is in here.]
Print "<tr>";
$x++;
}elseif($x == 2){
Print "</tr>";
}else(){
$x++;
}
Print '<td><img src="' .$info['img'] . '" width="210" height="157">';
Print "".$info['name'] . "</td>";
}
}
?>
</table>
Without the counter, the table is more of a single-column table going down.
You've got a few issues:
Syntax errors in your print lines, your concatenation (.) areas have inconsistencies with the type of quotes you're using to get back into the string e.g. ' or "
Identifying which column and where the break point is isn't really there
Try something like this (assume your database results are fine):
<table>
<?php
// ...
$i = 1;
$columns = 2;
while($info = mysql_fetch_array( $data )) {
if($i == 1) {
echo '<tr>';
}
echo '<td><img src="'.$info['img']. '" width="210" height="157">' . $info['name'] . '</td>';
if($i == $columns) {
echo '</tr>';
$i = 1;
} else {
$i++;
}
}
?>
</table>

unknown columns, column names, and rows into HTML table

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"

Categories