php - get second row until last row in mysql - php

Using while loop, i can get all the result in the table and echo it into a html table.
But, i want to skip the first row, and echo the result starting from second row.
How can i do that?
This is my code.
$sql2="select * from table where year = '2015' and month = '2' order by month desc";
$result2=mysqli_query($conn,$sql2);
echo '<table>';
while($row2=mysqli_fetch_assoc($result2))
{
echo '<tr>';
echo '<th>'.$row2['acc_sth_date'].'</th>';
echo '<th>'.$row2['acc_sth_med_ori'].'</th>';
echo '<th>'.$row2['acc_sth_med_new'].'</th>';
echo '<th>'.$row2['acc_sth_operator'].'</th>';
echo '</tr>';
}
echo '</table>';
Help me please master. Thanks

You can achieve that in two ways.
You could use LIMIT statement in your sql query :
$sql2="select * from table where year = '2015' and month = '2' order by month desc LIMIT 1,100";
1 = Start at the 2nd row
100 = Returns a maximum of 100 rows
Add a condition in your while loop :
$firstRow = true;
while ($row2 = mysqli_fetch_assoc($result2))
{
if (true === $firstRow)
{
$firstRow = false;
continue;
}
// ... Rest of your code ...
}

You need to add a variable that is tested and set to true to not allow skipping next time:
$FirstRun=true;
while($row2=mysqli_fetch_assoc($result2))
{
if ($FirstRun){
$FirstRun = false;
}else {
echo '<tr>';
echo '<th>'.$row2['acc_sth_date'].'</th>';
echo '<th>'.$row2['acc_sth_med_ori'].'</th>';
echo '<th>'.$row2['acc_sth_med_new'].'</th>';
echo '<th>'.$row2['acc_sth_operator'].'</th>';
echo '</tr>';
}
}

Use the following code
$sql2="select * from table where year = '2015' and month = '2' order by month desc";
$result2=mysqli_query($conn,$sql2);
$row2=mysqli_fetch_assoc($result2);
$count = count($row2);
$i = 1;
echo '<table>';
while(i>=$count)
{
echo '<tr>';
echo '<td>'.$row2[i]['acc_sth_date'].'</td>';
echo '<td>'.$row2[i]['acc_sth_med_ori'].'</td>';
echo '<td>'.$row2[i]['acc_sth_med_new'].'</td>';
echo '<td>'.$row2[i]['acc_sth_operator'].'</td>';
echo '</tr>';
$i++;
}
echo '</table>';
It will display all rows except the first row.

Related

how to create table with dynamic column using php

Suppose there is a number of item in array.which may be odd or even like I have an array which contain item from a to z Now I want to display that item in table . But As you know That There are 23 alphabets I want to display these alphabets in table which contains only 5 column in the last you got only three alphabets I want to display them in table . In the last I want that there should be three column not 5.
Here is my code i could not get that what should i do?
But the problem I faced in the below code is that the second loop is not correct.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$count= sizeof($arr);
$row=ceil($count/5);
echo "<table border='1'>";
for($r=0;$r<$row;$r++){
echo "<tr>";
for($j=0;$j<=5;$j++){
echo "<td>'".$arr[$j]."'</td>";
}
echo "</tr>";
}
echo "</table>";
?>
My approach uses array_slice to take out pieces of the source and build rows:
$arr=array('a','b','c','d','e','f','g','h');
$offset = 0;
$num_columns = 5; //adjust number of columns
$table_html = "<table border='1'>";
while($slice = array_slice($arr,$offset,$num_columns)){
$offset += $num_columns;
$row_html = '';
foreach($slice as $n) $row_html .= "<td>$n</td>";
$table_html .= "<tr>$row_html</tr>";
}
$table_html .= '</table>';
echo $table_html;
Live demo
Try below code. Declaring number of column required in a variable, so which can be changed any time. closing the tr tag when loop count is same as number of columns to be displayed.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$columnLength = 5;
echo "<table border='1'>";
echo "<tr>";
for($r=0;$r<count($arr) ; $r++){
echo "<td>'".$arr[$r]."'</td>";
if($r + 1 == $columnLength ) {
echo "</tr>";
}
}
echo "</table>";
?>

PHP Loop Detect First Instance of each Letter of MySQL results

If I query a database with PHP using MySQLi, how can I detect the first instance of each letter of the alphabet?
If I have a table like -
ID | name
1 Allen
2 John
3 Sally
4 William
and I query
SELECT * FROM table ORDER BY name ASC
Can I have something in my loop that says "if this is the first time you've seen the string in name start with the letter A", echo <a id="a"></a> to create an anchor tag? Then it will proceed to do the same for B,C,D,E,F,G, etc.. Then I can create an alphabetical legend.
Here is my query and loop:
$query = "SELECT * FROM table ORDER BY name ASC";
$result = $db->query($query);
$num = $result->num_rows;
for($i=0; $i < $num; $i++){
$row = $result->fetch_object();
//IF THIS IS THE FIRST TIME SEEING $row->name START
//WITH A DIFFERENT LETTER OF THE ALPHABET ECHO SOMETHING...
echo $row->name;
}
Create an associative array that records which letters you've seen.
$letters_seen = array();
while ($row = $result->fetch_object()) {
$letter = substr($row->name, 0, 1);
if (!isset($letters_seen[$letter])) {
// This is the first time seeing this initial letter
$letters_seen[$letter] = true;
echo "<a id='$letter'>$letter</a>";
}
echo $row->name;
}
Since your results are ordered by name, if the first letter of the current row doesn't match the first letter of the previous row, then you know it's the first time you've seen it.
$previousLetter = '';
for($i=0; $i < $num; $i++){
$row = $result->fetch_object();
if($row->name[0] != $previousLetter) {
echo "<a id='" . $row->name[0] . "'></a>";
$previousLetter = $row->name[0];
}
echo $row->name;
}

loop to populate html table vertically [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I have a mysql query that returns an array of rows. How would i populate my html table using php vertically? there is no limit to how many columns i my HTML table allowed.
My MYSQL query returns about 40 columns per row.
MYSQL row1 => 10|11|12|13|14|15|16|17|18|19
row2 => 20|21|22|23|24|25|26|27|28|29
row3 => 30|31|32|33|34|35|36|37|38|39
HTML output should look like this
10 | 20 | 30
11 | 21 | 31
12 | 22 | 32
13 | 23 | 33
14 | 24 | 34
15 | 25 | 35
16 | 26 | 36
17 | 27 | 37
18 | 28 | 38
19 | 29 | 39
this is my code, and it's displaying nothing.
$values = array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$numrows = $_db->num_rows($result);
$c = 1;
while ($c <= $numrows)
{
$values['col_'.$c] = array();
$c++;
}
$r = 1;
while ($row = $_db->fetch_array($result))
{
$values['col_'.$c][$r] = $row;
$r++;
}
echo "<table border='1'>";
for ($r = 1; $r <= $numrows; $r++)
{
echo "<tr>";
for ($c = 1; $c <= sizeof($values['col_1']); $c++)
{
echo "<td>".$values['col_'.$c][$r]."</td>";
}
echo "</tr>" ;
}
echo "</table>" ;
Any idea what i'm doing wrong? or how to make it simpler? (i think there are too many while loops)
I think what you want is creating the php array from the mysql query, transposing the array (like you would transpose a matrix) and display it.
Transposing an array is a solved problem (transposing multidimentional arrays in php)
For the rest, it is pretty simple ... here is my code:
$res = mysqli_query(...);
$anarr = array();
while ($row = mysqli_fetch_array($res,$result_type=MYSQLI_ASSOC)){
$anarr[] = $row;
}
// here is the transpose part
array_unshift($anarr, null);
$transposedarr = call_user_func_array('array_map', $anarr);
// end of the transpose part
echo '<table>';
foreach ($transposedarr as $r){
echo '<tr>';
foreach ($r as $c){
echo '<td>'.$c.'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
You are assigning only one row in your while loop. Change that with below code:
while ($row = $_db->fetch_assoc($result))
{
$values['col_'.$c][$r] = $row;
$c++;
$r++;
}
Here you are assigning the value to $value['col_1'][$r] and not increasing the value of $c. So at the end it override the values.
You can simplify the problem by just saying
$values[$rowIndex] = $columnArray
So in this case
$values[0] = array( 10, 20, 30 );
$values[1] = array( 11, 21, 31 );
And then loop across each array
echo "<table border='1'>";
foreach( $values as $row )
{
echo "<tr>";
foreach( $row as $columnValue )
{
echo ..whatever..
}
echo "<tr>";
}
echo "</table>" ;
Or something along these lines. I just basically psuedo coded this though, I have no access to php interpreter right now.
//while and foreach loop can do this
<?php
$values = array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$numrows = $_db->num_rows($result);
//check here
if($numrows>0)
{
//1 row
$r = 1;
//column
$c=0;
while ($row = $_db->fetch_assoc($result))
{
//value row column
$values[$r][$c] = $row;
//column == 3
if($c==2)
{
//increase row
$r++;
//reset column
$c = 0;
}else{
$c++;
}
}
echo "<table border='1'>";
//display row and columns
foreach($values as $row)
{
echo "<tr>";
echo "<td>".$values[0]."</td>";
echo "<td>".$values[1]."</td>";
echo "<td>".$values[2]."</td>";
echo "</tr>" ;
}
echo "</table>" ;
}
You can do everything in a single loop. Additionally, at least for your purposes in this example, I don't understand why you're putting everything in an array and then echo, instead of echoing it directly.
e.g. (tested):
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
echo "<table border='1'>";
$tab = array();
while ($row = $result->fetch_row())
{
$tab[] = $row;
}
for( $i = 0, $l = count($tab[$i]); $i < $l; $i++){
echo "<tr>";
for( $j = 0, $m = count($tab); $j < $m; $j++){
echo "<td>".$tab[$j][$i]."</td>";
}
echo "</tr>" ;
}
echo "</table>";
UPDATE: I completely changed my code. I didn't get initially what you needed.
Does this code help you?
This is how I would tackle it. The most difficult part is preparing the structure in which you prepare the table. It uses the following syntax: $somearray[] = $x, which appends $x to array $somearray. implode() concats an array together with a string you define. Last but not least, you were using mysql_fetch_assoc, which returns an associative array (Array( [column1] => "val1" ); etc). You want a numbered array instead for these kind of operations. This can be accomplished with mysql_fetch_array with a second argument of MYSQL_NUM.
$arrayOfRows = Array();
$sql = "SELECT * FROM `TABLE_NAME` ORDER BY `id` ASC LIMIT 0,12";
$result = $_db->query($sql);
$firstrun = true;
while( $row = $_db->fetch_array($result, MYSQL_NUM) ) {
#Setup structure on first run
if( $firstrun ) {
$firstrun = false;
for( $i = 0; $i < count( $row ); $i++ ) {
$arrayOfRows[$i] = Array();
}
}
#Each field in this mysql row needs to be in a different html row
foreach( $row as $k => $v ) {
$arrayOfRows[$k][] = $v;
}
}
#Now simply print it
echo '<table>';
foreach( $arrayOfRows as $k => $row ) {
echo '<tr>';
echo '<td>' . implode( '</td><td>', $row ) . '</td>';
echo '</tr>';
}
echo '</table>';
<?php
$arr = array(array(1,2,3,4,5,6,7,8,9), array(10,11 etc . . .
for($i = 0; $i < 9; ++ $i){
for($x = 0; $x < $num_rows; ++ $x){
echo $arr[$x][$i];
}
echo '<br/>';
}
?>
U may replace 9 with number of columns in tables
I not shure what it this code correct (can't test now), but i think it can help you
Sorry if i do something wrong, i just try to help

mysql php columns

<?php
$say = array("ann","brenda","charles","david",
"edward","florence","geoff","harry",
"ingrid","james","kelly","liam");
$columns = 5;
for ($p=0; $p<count($say); $p++) {
// Start of table or line?
if ($p==0) { // Start of table
print "<table border=0><tr>";
} elseif ($p%$columns == 0) { // Start of row
print "<tr>";
}
print "<td>".htmlspecialchars($say[$p])."</td>";
// End of table or line?
if (($p+1)%$columns == 0) { // End of row
print "</tr>";
}
if ($p==count($say)-1) { // End of table
$empty = $columns - (count($say)%$columns) ;
if ($empty != $columns) {
print "<td colspan=$empty> </td>";
}
print "</tr></table>";
}
}
?>
The result:
ann brenda charles david edward
florence geoff harry ingrid james
kelly liam
I'm trying to do the same with mysql
so far i got
<?php
$con = mysql_connect("localhost","root","lol");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$nam=$row['nam'];
$columns = 3;
for ($p=0; $p<count($id); $p++) {
// Start of table or line?
if ($p==0) { // Start of table
print "<table border=0><tr>";
} elseif ($p%$columns == 0) { // Start of row
print "<tr>";
}
print "<td>".$nam."</td>";
// End of table or line?
if (($p+1)%$columns == 0) { // End of row
print "</tr>";
}
if ($p==count($nam)-1) { // End of table
$empty = $columns - (count($nam)%$columns) ;
if ($empty != $columns) {
print "<td colspan=$empty> </td>";
}
print "</tr></table>";
}
}
}
mysql_close($con);
?>
Result:
ann
brenda
charles
david
edward
florence
geoff
harry
ingrid
james
kelly
liam
Question: what's wrong?
Dabase table
id nam
1 ann
2 brenda
3 charles
4 david
5 edward
6 florence
7 geoff
8 harry
9 ingrid
10 james
11 kelly
12 liam
I'd suggest that you split your code into two distinct functions.
One function will read information from the database or the array, the other will format the output.
Right now, it looks an awful lot like you took your first chunk of code and put it into the middle of the while loop in the second piece.
MySQL is returning results to you, one result row at a time. So what you should do is collect all those results first and then print them out second (either that, or make a counter on the number of rows returned). In your second piece of code, you're treating each result row as you were the entire array of results in the first piece.
That is, the line while($row = mysql_fetch_array($result)) returns a single row from the table.
Because of this, the line $id=$row['id']; does not assign an array to $id.
Because of this, the line for ($p=0; $p<count($id); $p++) { iterates over a single item, resulting in what you're seeing.
My code still looks a little hackish, but it may give you an idea. I'm afraid I haven't tested it.
print "<table><tr>";
$p=0;
$columns=3;
while( $row = mysql_fetch_array($result) ) {
if ( $p>0 && ($p % $columns)==0 )
print "</tr><tr>";
print "<td>{$row['nam']}</td>";
$p++;
}
for(true;($p % $columns)!=0;$p++) //Finish off $p from above
print "<td> </td>";
print "</tr></table>";
To do this in a more modular way:
function display($stuff,$cols){
//Make sure the table is some multiple of $cols to eliminate special cases
//Hackish
while( (count($stuff) % $cols)!=0 )
$stuff.push_back(" ");
//Start table and first row, eliminating another special case
print "<table><tr>";
for($i=0;$i<count($stuff);$i++){
if($i>0 && ($i % $cols)==0)
print "</tr><tr>";
print "<td>{$stuff[$i]}</td>";
}
print "</tr></table>";
}
$names=array()
while( $row=mysql_fetch_array($result) )
$names.push_back($row['nam']);
display($names,5);

PHP/MySQL news archive

I'm a bit stuck trying to get my code to output correctly, see below. It all works ok, but rather than displaying all news items, it only shows one for each month. What I need to do is group all news for a selected month with the month/year heading for that month. Hope this makes sense.
Any help greatly appreciated.
SS
$theQuery="Select * from isnews WHERE active = '1' GROUP BY YEAR(date) DESC, MONTH(date) ORDER BY YEAR(date) DESC, MONTH(date) DESC";
$newsQuery=mysql_query($theQuery);
if(mysql_num_rows($newsQuery)>0) {
while ($newsResult=mysql_fetch_array($newsQuery)) {
$newDate = $newsResult['date'] ;
echo '<div class="date">' . date('F Y ',strtotime($newDate)) . '</div>';
echo '<ul class="press">';
echo '<li>
<img src="'.$wwwUrl.'images/news/'.$newsResult['image'].'" width="'.$newsResult['tnWidth'].'" height="'.$newsResult['tnHeight'].'" title="'.$newsResult['title'].'" alt="'.$newsResult['title'].'" />
<h3>'.$newsResult["title"].'</h3>
'.substr($newsResult['descrip'],0,100).'
<p>Read more</p>
</li>';
}
echo '</ul>';
} else {
echo 'We currently have no press releases available';
}
There are two problems that I can see. First of all, GROUP BY is an aggregate function, so it is used to combine multiple rows into one row in your result (for instance, if you wanted to see how many news items were written for a given month and year). Secondly, even if you were getting multiple records per time period, you are outputting a date header for every record that you pull from the database (ie. you would get duplicate headers if you have multiple news items from the same month and year).
A better solution would be to collect all your active news items (without the GROUP BY clause), and then build an array which you can then iterate over to output your page:
$query = "SELECT *
FROM isnews
WHERE active = '1'
ORDER BY YEAR(date) DESC, MONTH(date) DESC";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
while ($newsResult = mysql_fetch_array($resultSet))
{
// The time period is what you will output as your header
$timePeriod = intval(date("F Y", $newsResult['date']));
if (!isset($newsArray[$timePeriod]))
{
// Create a subarray if needed
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
echo '<div class="date">' . $timePeriod . '</div>';
echo '<ul class="press">';
foreach ($newsItems as $item)
{
echo '<li>';
// ... do your news item outputting
echo '</li>';
}
echo '</li>';
echo '</div>';
}
}
else
{
echo 'We currently have no press releases available';
}
Many thanks for the help.
I've tried adapting the code from Daniel a little in order to create a sidebar-type archive list showing years, then the months and their corresponding news results. The end result being an accordion type menu where the years dropdown to show the months, then the months dropdown to display the news items. I can get it to work as far as the years go but can't seem to get the months working properly.
Any pointers/help more than greatly appreciated. (code below)
SS
$query = "SELECT * FROM isnews WHERE active = '1' ORDER BY YEAR(date) DESC, MONTH(date) DESC";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
echo '<ul>' . PHP_EOL;
echo '<li><strong>Press releases:</strong></li>' . PHP_EOL;
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['date'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$timePeriodY = date('Y',strtotime($timePeriod));
$timePeriodM = date('F',strtotime($timePeriod));
if (!isset($newsArray[$timePeriodY]))
{
$newsArray[$timePeriodY] = array();
}
$newsArray[$timePeriodY][] = $newsResult;
}
foreach ($newsArray as $timePeriodY => $newsItems)
{
echo '<li><em>' . $timePeriodY . '</em>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
foreach ($newsItems as $item)
{
echo '<li>';
echo ''.$item["title"].'';
echo '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
else
{
echo 'We currently have no press releases available';
}
it only shows one for each month
That's correct, your GROUP BY isn't correct. All columns (see the * ) should be in your GROUP BY because all of them are in the SELECT and you don't use any aggregate function. MySQL has very strange behaviour and now only returns the first record it can find.
If you want all records, just drop the entire GROUP BY, and ORDER BY the month and year to get the correct sort order. In youw PHP you can make some groups, but that has nothing to do with SQL.
You might consider ONLY_FULL_GROUP_BY, this helps to prevent strange/false results.

Categories