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

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

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 create HTML table from multiple inputs from user?

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);
?>

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>";
}

displaying values from database into an html table

i want to display values from a database (a list of categories) into a table that has 2 columns and x number of rows.
I want my web page to display like this:
Apes Cats
Apples Cherries
Bats Tigers
Berries Zebras
Instead of
Apes Apples
Bats Bears
Cats Cherries
Tigers Zebras
Here is my code so far:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
while ($category = mysqli_fetch_array($data)) {
?>
<tr>
<td><?php echo $category['cat_name'] ?></td>
</tr>
<?php } ?>
</table>
Here's the basic idea:
You get the count of the data via num_rows
Divide by two.
Now, the result of your division will be the number of rows.
Output a loop echoing value for row x and x+ num rows. For example the output of line 1 would be :
<tr><td>$row[val1][data]</td><td>$row[val5][data]</td></tr>
So, your loop would ultimately output:
val 1 | val 5
val 2 | val 6
val 3 | val 7
val 4 | val 8
The loop should end when your incrementing variable = num_rows. Should be pretty straightforward from there. Good luck.
Try this (haven't tested it though):
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
# Calculate total rows and half rows, rounded up
$full_row_count = mysqli_num_rows($data);
$half_row_count = ceil($full_row_count / 2);
$i = 0;
while ($i <= $half_row_count) {
# Set the result pointer for first column ...
mysqli_data_seek($data, $i);
$category_1 = mysqli_fetch_array($data);
# ... then calculate the offset for the second column ...
$col_2_offset = $i + $half_row_count;
# .. and make sure it's not larger than total rows - 1
if ($col_2_offset <= $full_row_count - 1) {
mysqli_data_seek($data, $col_2_offset);
$category_2 = mysqli_fetch_array($data);
} else {
$category_2 = array('cat_name' => '');
}
?>
<tr>
<td><?php echo $category_1['cat_name'] ?></td>
<td><?php echo $category_2['cat_name'] ?></td>
</tr>
<?php
$i++;
}
?>
</table>
Hope this helps !
You can add an another variable say, $i, to the loop and just increment this through as follows:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$i=1;
while ($category = $data->fetch_row()) {
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $category[1] ?></td>
</tr>
<?php
$i++;
} ?>
</table>
EDIT: Updated to fetch row data for each result and assume that cat_name is the second item in the array i.e. $category[1].
If it doesn't have to be a table and your fine with browsers that support CSS 3, then you can use CSS columns:
http://jsfiddle.net/QKuDL/
Otherwise you'll need to sort the results first (untested - PHP is not my strong suit):
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$col_count = 2;
$max_items_per_col = ceil( mysqli_num_rows ( $data ) / $col_count );
$cols = array(array());
$col = 0;
while ($category = mysqli_fetch_array($data)) {
if (count($cols[$col]) >= $max_items_per_col) {
$col++;
}
$cols[$col][] = $category['cat_name'];
}
?>
<table> <!-- all of those attributes should be CSS instead -->
<?php for ($i = 0; $i < $max_items_per_col; $i++) { ?>
<tr>
<?php foreach ($cols as $col) { ?>
<td><?php if(isset($col[$i])) echo $col[$i]; ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$midpoint = ceil($data->num_rows / 2);
$i=0;
while ($category = $data->fetch_array()) {
if ($i < $midpoint)
$left[$i] = "<td>" . $category['cat_name'] . "</td>";
else
$right[$i - $midpoint] = "<td>" . $category['cat_name'] . "</td>";
$i++;
}
print "<table>";
for ($j=0; $j < $i; $j++)
{
print "<tr>" . $left[$j];
if (array_key_exists($j, $right)) print $right[$j];
print "</tr>";
}
print "</table>";

Echo current number of row

My $num_rows echos the total row count but I want the current row number.
<?php
$result = mysql_query('SELECT * FROM texts ORDER BY id desc');
while($row = mysql_fetch_array($result)){
$num_rows = mysql_num_rows($result);
?>
<tr class="alt">
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['title']; ?></td>
<td>Original</td>
<td>#English</td>
<td><?php echo $num_rows; ?></td>
</tr>
<?php
}
?>
Thank you :)
why you should not use a increment variable to count the loop turns inside while?
$tmpCount = 1;
while() {
$tmpCount ++;
}
Is this helpful to you? or are you expecting the physical row number of from database?
If you want to just number the rows returned by the query (instead of using the actual ID - $row['id'] presumably), you can just increment a number with each row:
$num_rows = 0;
while ($row = mysql_fetch_array($result)){
$num_rows++;
// ...
This works, but when sorting, the number gets locked in and doesn't return to the natural sort. The initial sort will be 1, 2, 3 but when clicking on the column to sort, whatever row is associated with the first sort will stay with it and the new sort will not have the num_rows in order!

Categories