How to create HTML table from multiple inputs from user? - php

I have created simple html form which has two major inputs:
Checkbox for multiple choices (for info: user can select multiple districts)
radio button for single input (for info: user after marking the checkbox in step one will now chose another only one input)
after this Table should be generated:
Note: Multiple tables have same column name so that the displayed table will include the merged data for selected district names
Till now, I have created table for only one district i.e. for individual district. (my database resides in PostgreSQL)
This is database connection for my Table:
$db = pg_connect('host=localhost port=5433 dbname=MergedDB user=postgres password=admin');
I have two array for my table:-
$userclass = array('0-5','6-10','11-15', '>15','Total');
$btotal = array();
The query fetching code is:-
$query = " select * from "Arscenic_Test"
.
.
.
/* some query here*/";
$btresult = pg_query($db, $query);
while($btresults = pg_fetch_row($btresult)){
$count = count($btresults);
$y = 0;
while ($y < $count)
{
$c_row = current($btresults);
$btotal[] = $c_row;
next($btresults);
$y = $y + 1;
}
}
And my HTML table is:-
<?php
for($i=0; $i<5; $i++){
?>
<tr>
<td><?php echo $userclass[$i];?></td>
<td><?php echo $btotal[$i];?></td>
<td><?php echo $perb10[$i];?></td>
<td><?php echo $bettotal[$i];?></td>
<td><?php echo $pbet[$i];?></td>
<td><?php echo $b51_100total[$i];?></td>
<td><?php echo $pb51_100[$i];?></td>
<td><?php echo $bt101_300total[$i];?></td>
<td><?php echo $pb101_300[$i];?></td>
<td><?php echo $abov300total[$i];?></td>
<td><?php echo $pabov300[$i];?></td>
<td><?php echo $total[$i];?></td>
<td><?php echo $ptotal[$i];?></td>
</tr>
How to give User a multiple choices and generate the table as per his inputs?

First of all fetch all the districts from the database and render it to the html table. Then you can choose different district from drop-down menu.
Sample Code:
<?php
$con=mysqli_connect("localhost","nalin","nalin123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT district FROM District");
echo "<table border='1'>
<tr>
<th>District</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['district'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Related

How do I calculate the total of a query result in php?

I was wondering if I could get some help echoing the sum of each column based on a query result. Screenshot of table output
<?php
if ($stationid=="") {
$query = "select * from " . $tablename . " where date_created >= '" . $startdate . "' and date_created <= '" . $enddate . "' and status='1' order by id desc"; ?>
$result = do_query($query);
$total = mysql_num_rows($result);
if ($total>0) {
while($row = do_fetch_result($result)){
?>
<?php
$sum_static = $row['SUM(element_10)'];
$sum_gif = $row['SUM(element_11)'];
$sum_ibv = $row['SUM(element_12)'];
$sum_html5 = $row['SUM(element_13)'];
$sum_landing = $row['SUM(element_14)'];
$sum_revs = $row['SUM(element_15)'];
?>
<tr>
<td><?php echo $sum_static; ?></td>
<td><?php echo $sum_ibv; ?></td>
<td><?php echo $sum_gif; ?></td>
<td><?php echo $sum_html5; ?></td>
<td><?php echo $sum_landing; ?></td>
<td colspan=1><?php echo $sum_revs; ?></td>
</tr>
Simply specify columns name with aggregate function.
SELECT SUM(column1),SUM(column2)
FROM tablename
<?php
$overallstatic="0";
$overallgif="0";
$overallibv="0";
$overallhtml5="0";
$overalllanding="0";
$overallrev="0";
<?
<?php
$overallstatic=$overallstatic+$row['element_10'];
$overallgif=$overallgif+$row['element_11'];
$overallibv=$overallibv+$row['element_12'];
$overallhtml5=$overallhtml5+$row['element_13'];
$overalllanding=$overalllanding+$row['element_14'];
$overallrev=$overallrev+$row['element_15'];
?>
<?php
<td><?php echo $overallstatic; ?></td>
<td><?php echo $overallibv; ?></td>
<td><?php echo $overallgif; ?></td>
<td><?php echo $overallhtml5; ?></td>
<td><?php echo $overalllanding; ?></td>
<td colspan=1><?php echo $overallrev; ?></td>
?>
This worked.
If we need to calculate sum from individual rows (if all we want to return is totals, then this is not the most efficient way to get totals), we could initialize the $sum_foo variables to zero...
$sum_static = 0;
$sum_foo = 0;
And then for each row fetched, add the column value to the running total.
$sum_static += $row['static'];
$sum_foo c += $row['foo'];
After the last row is fetched, the $sum_foo variables will have the total for that column for all rows.
In terms of performance, this is a very inefficient way to get just totals. We can have the database return the totals. We ditch the * in the SELECT list, and specify aggregate functions in the SELECT list:
SELECT SUM(static) AS sum_static
, SUM(foo) AS sum_foo
FROM ...
Execute the query, and fetch the one row that is returned, and the row will have the precomputed totals...
$row['sum_static']
$row['sum_foo']

How to get first id from the fetched rows in php mysql?

I am fetching data in php from mysql table. Let say I retrieved 15 rows containing 15 unique ids. Now I want to get the the very first fetched id from the results.
This is what I'm trying..but its giving me the last id
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
while($row = $results->fetch_assoc()){
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
you could simply add index like this
$i = 0;
while loop
$i++;
if($i === 1)
{get ID}
//rest of your while loop
endwhile;
you can modify your sql to
SELECT * FROM orders where Sales_Rep='$sales_rep' Order By Order_ID DESC
or you use this code
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
$i =0;
$first_id = 0;
while($row = $results->fetch_assoc()){
if ($i===0){
$first_id = $row["Order_ID"];}
$i++;
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
your first Id is in $first_id

PHP - How can I print out my database table?

I have a php code to print out my table including its column name. The printing has to be dynamic because it has to print different size/length tables based on a user input. :
<table>
<?php
while ($row = mysqli_fetch_array($results)) {
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<td> <?php echo $row[$fieldInfo->name] ?> </td>
<?php }
} ?>
</table>
this is the query for $results:
$tName = $_POST["tableNames"]; //this data is recieved from another page
require_once("conn.php");
$sql = "SELECT * FROM $tName";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
my code correctly prints out the table name as well as the first row data but it is not formatted correctly here is how it looks:
additionally. for some reason it only prints out the first row even though im using a while loop.
My advice to you is to prepare two arrays:
First one: containing column names and second: containing data.
When use two foreach to generate first row with header and second one to display data. You have forgot to add <tr> tags to divide rows.
Use
The mysqli_fetch_field() function returns the next column in the result set as an object. It will only returns all column names not the records of table.
You need to use mysqli_fetch_array() for getting all records:
while ($info = mysqli_fetch_array($results,MYSQLI_ASSOC)) {
{
echo $info['rid'];
echo $info['level'];
....
}
I ended up with using a taras' suggestion of storing the column names in an array:
<table>
<?php
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<?php
$colNames[] = $fieldInfo->name;
?>
<?php }
while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<?php for ($i=0; $i<sizeof($colNames); $i++) { ?>
<td><?php echo $row[$colNames[$i]] ?>
<?php } ?>
</tr>
<?php } ?>
</table>
As of my understand, do you want to display all table and their columns?
So you can format like below
$sql = "SHOW TABLES FROM dbname";
$result_tables = mysqli_query($link, $sql);
echo "<table border=1>";
echo "<tr><td>Table name</td><td>Fields name</td></tr>";
while($row = mysqli_fetch_array($result_tables)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
$sql2 = "SHOW COLUMNS FROM ".$row[0];\\row[0] is used to get table name
$result_fields = mysqli_query($link, $sql2);
echo "<td>";
while($row2 = mysqli_fetch_array($result_fields)) {
echo $row2['Field'].',';
}
echo "</td>";
echo "</tr>";
}

do while in do while in php

That loop using do while, and it is working fine but when I add another do while in to this the second do while work but first do while only show one row not all 10 row. My code is below
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<?php do { ?>
<td><?php echo $row_Recordset1['nav']; ?></td>
<?php } while ($row_Recordset1= mysql_fetch_assoc($Recordset1)); ?>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
My date should be displayed once in a row but all the other td will be took from nav;
This is what I want:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
|2014-02-25|3.1|1.2|1.5|
But I'm currently getting:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
You should look at http://php.net/mysql_fetch_assoc
It moves the internal pointer one step ahead, so each time you do mysql_fetch_assoc() you get the next value, hence only your enternal do while is executed. That is, only date from the first row is output, and all other values are output in second do while;
Try this for exercise:
$q = mysql_query("SOME MYSQL QUERY WITH MINIMUM THREE ROWS");
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
print_r($f);
First of all, please don't bounce in and out of PHP like that...
<?php
do {
echo '<tr>
<td>';
echo $row_Recordset1['date'];
echo '</td>';
do {
echo '<td>';
echo $row_Recordset1['nav'];
echo '</td>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
echo '</tr>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
?>
Where do you fetch your first $row_Recordset1? Somewhere earlier than this code? You're going to output table cells (<td>) until you run out of rows. I don't think you want that.
Like so:
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<td><?php echo $row_Recordset1['nav']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Because each time you use mysql_fetch_assoc it does the following
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Part of the reason this doesn't work is because you are re-assigning the value of the same variable. If you don't want to lose it then you cannot do it this way. At the very least it is a bad idea if you ever intend to do anything new with the code.
Next, I really recommend you populate an array with the data first before you ever do anything with outputting it. It is a very good idea to separate logic from output.
Your code should look more like this:
<?php
//Assumes you have already connected to a mysqli resource
$conditional_data_filtered = $mysqli->real_escape_string($conditional_data);
$sql = "SELECT date, nav FROM some_table WHERE some_column = '" . $conditional_data_filtered . "'";
if ($result = $mysqli->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$data = array(); //Make sure we start with a fresh array each time.
$data['date'] = $row['date'];
//Now I think you have a bunch of data in the nav you need to loop through
$nav_filtered = $mysqli->real_escape_string($row['nav']);
$subSql = "SELECT some_data FROM navigation WHERE some_identifier = '" . $nav_filtered . "'";
if ($subResult = $mysqli->query($subSql)) {
while ($subRow = $subResult->fetch_assoc()) {
$data['nav'][] = $subRow;
}
}
$rowList[] = $data;
}
/* free result set */
$result->free();
}
foreach ($rowList as $rowData) {
echo "<tr>";
echo "<td>" . $rowData['date'] . "</td>";
foreach ($rowData['nav'] as $navData) {
echo "<td>" . $navData['some_info'] . "</td>";
}
echo "</tr>";
}
?>
Just a note: If you really don't have sub-data and just want to output the next column then you don't need a sub-loop. You just need to echo the contents of the column like you did with the first one. Then you can get rid of the sub-loops I have shown above and just put it within the first loop.

How to pass options value from each table row?

I am creating a table with rows which has options in each cells. The options are received from database table. Since each row has a options cell, I have to receive the value from each row. In select tag, the 'name' is incremented with the rows. But I am only getting the value of the last row.
Attaching the code section here.
for ($i = 1; $i <= $_GET['pno']; $i++) {
echo'<tr>';
echo "<td>$i</td>";
echo '<td><select name="prod_$i">'; echo "prod_$i";
//Query for production table gets processed.
$qry_pr="SELECT * FROM production";
$result_pr=mysql_query($qry_pr);
$rows_pr=mysql_affected_rows($con);
//Production options get filled from the table data.
for($j=0;$j<=$rows_pr;$j++)
{
$res_arr_pr=mysql_fetch_array($result_pr);
echo "<option value=$res_arr_pr[0]>$res_arr_pr[1]</option>";
//$res++;
}
//mysql_close($con);
echo '</select></td>';
echo '<td><select name="prod_mu_$i">';
//Query for measurement_unit table gets processed.
$qry_mu="SELECT * FROM measurement_unit";
$result_mu=mysql_query($qry_mu);
$rows_mu=mysql_affected_rows($con);
//Unit options get filled from the table data
for($k=0;$k<=$rows_mu;$k++)
{
$res_arr_mu=mysql_fetch_array($result_mu);
echo "<option value=$res_arr_mu[0]>$res_arr_mu[1]</option>";
}
echo '</td>';
echo '</tr>'; echo "prod_$i";
}
echo'</table><br>';
Hope I am clear with the query.
Thank you.
You have placed the SQL Query inside the for loop making it heavy. Because it will perform the same query over and over again. If you tweak the code a little you can use perform a single query and use that for all loop iterations.
<?php
//initialize blank
$productions = $measurements = '';
// create the production select box
$qry_pr="SELECT * FROM production";
$result_pr=mysql_query($qry_pr);
if( mysql_num_rows($result_pr) )
{
$productions .= "<select name='prod_%index%'>";
while( $rec_pr = mysql_fetch_row($result_pr) )
{
$productions .= "<option value='{$rec_pr[0]}'>{$rec_pr[1]}</option>";
}
$productions .= "</select>";
}
// create the measurement select box
$qry_mu="SELECT * FROM measurement_unit";
$result_mu=mysql_query($qry_mu);
if( mysql_num_rows($result_mu) )
{
$measurements .= "<select name='prod_mu_%index%'>";
while( $rec_mu = mysql_fetch_array($result_mu) )
{
$measurements .= "<option value='{$rec_mu[0]}'>{$rec_mu[1]}</option>";
}
$measurements .= "</select>";
}
?>
<table>
<?php for($i=1;$i<=$_GET['pno'];$i++): ?>
<tr>
<td><?php echo str_replace('%index%',$i,$productions); ?></td>
<td><?php echo str_replace('%index%',$i,$measurements); ?></td>
</tr>
<?php endfor; ?>
</table>
Change:
echo '<td><select name="prod_$i">'; echo "prod_$i";
to:
echo '<td><select name="prod_' . $i . '[]">'; echo "prod_$i";
mysql_affected_rows will only give you the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query. Your performing a SELECT, so the $rows_mu value will be wrong.
Instead of:
$rows_mu=mysql_affected_rows($con);
//Unit options get filled from the table data
for($k=0;$k<=$rows_mu;$k++)
{
$res_arr_mu=mysql_fetch_array($result_mu);
echo "<option value=$res_arr_mu[0]>$res_arr_mu[1]</option>";
}
try this:
//Unit options get filled from the table data
while ($res_arr_mu = mysql_fetch_array($result_mu))
{
echo "<option value=$res_arr_mu[0]>$res_arr_mu[1]</option>";
}

Categories