mysql php columns - php

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

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

Sort CSV file and display in HTML table with PHP

I have a CSV file that has (dummy) data like this:
Mike Judge, Office Space, Comedy
Larry Wachowski, Matrix Zero, Action
Sofia Coppola, Lost In Translation, Drama
Ron Howard, A Beautiful Mind, Drama
Joe Biden, Your Big Hat, Sports
Barack Obama, The Stubborn Goat, Drama
Steve Smith, 2 Beautiful Ants, Suspense
Jared Hess, Napoleon Dynamite, Comedy
Jack Daniels, Field of Dreams, Drama
I need the 1st field sorted alphabetically by last name. That works.
Then I need to show the array in an HTML table and be able to set the number of columns to perhaps 5. I need each cell to hold one line from the CSV file, then move left to right filling the table.
Everything I've tried gets me almost there, but the table does not display properly - it has missing td tag or no in the last td.
Any help would be appreciated.
Here's what I have so far:
$file = fopen("dummy-list.csv", "r") or die('cannot open file');
// sort
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($file, 0, ',') )) {
//extract surname from the first column
//this should match the last word before the comma, if there is a comma
preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
$surnames[] = $m[1];
$rows[] = $row;
}
//fclose($file);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
//print_r($rows);
// set # of table columns
$numCols = 4;
$i=0;
echo '<table border="1" align="center"><tr>' . "\n";
foreach( $rows as $rows2 )
{
if ($i % $numCols == 0 && $i != 0)
echo "</tr>\n<tr>"; // every time but the first
echo '<td>';
foreach( $rows2 as $key )
{
echo $key . '<br />';
$i++;
}
echo "</td>\n";
}
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
// end table
echo '</tr></table>' . "\n\n\n";
Stay with your code:
Change this:
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
For it:
$mod = $numCols-count($rows)%$numCols;
for($i=0;($i < ($mod) && $mod != $numCols);$i++)
echo '<td> </td>' . "\n";
And solve your problems!
You just need to modify your logic slightly. Currently, your script doesn't track which column your in, so it has no way of knowing how many cells to pad.
The biggest logical problem is:
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
All that is doing is checking that the number of columns is devisable by $i. so, after $i gets to 3, it stops. (in this case 4/3 != 0)
The following works:
$file = fopen("dummy-list.csv", "r") or die('cannot open file');
// sort
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($file, 0, ',') )) {
//extract surname from the first column
//this should match the last word before the comma, if there is a comma
preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
$surnames[] = $m[1];
$rows[] = $row;
}
//fclose($file);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
//print_r($rows);
// set # of table columns
$numCols = 4;
$i=0;
$cellpos = 0; //count columns
echo '<table border="1" align="center"><tr>' . "\n";
//use the amount of rows as a divisor
for($c=0; $c<Count($rows); $c++ )
{
if ($i % $numCols == 0 && $i != 0){
echo "</tr>\n<tr>"; // every time but the first
$cellpos=0; //reset our column position
}
echo '<td>';
//then, call each csv row explicitly
foreach( $rows[$c] as $key )
{
echo $key . '<br />';
$i++;
}
echo "</td>\n";
$cellpos++; //track our column position
}
while ($cellpos++ < $numCols)
echo '<td> </td>' . "\n"; // fill in empty cells
// end table
echo '</tr></table>' . "\n\n\n";
I added $cellpos variable to count the td in each row, as your populating. It gets reset every time you start a new row. if you track that var through the script you will see my changes.
Additionally, if you want to do something more specific with those keys, you can call them directly instead of just looping over the row. Just change the code between <td> tags.
echo '<td>';
//then, call each csv celldata explicitly
echo '<img src="'. $rows[$c][1] . '" /><br />' .$rows[$c][2] . '';
$i++;
echo "</td>\n";
You can use the MOD operator to check if you are at the end of a column and then end the row, and start a new one:
$cols = 4;
$count = count($rows);
$table_html ="<tr>";
for($i=0; $i < $count; ++$i){
$table_html.= '<td>' . implode("<br>", $rows[$i]) . '</td>';
if($i != 0 && ($i % $cols == 0)){
$table_html.="</tr>";
}
}
$table_html.="</tr>";
echo $table_html;

Printing output in Table with alternate row colors in PHP

So my code is below.The for loop is concatenating the elements from 2 arrays and printing them in a table.
I have 2 questions:
1) Although the output is correct I would like to print the output by calling the first function (fullname) in the second function (printTable).
2) I would like to print the output that is in the table rows in alternate colors of red and green.
<?php
$firstname=
array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");
$lastname=
array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");
function fullname($fname,$lname){
for ($i=0; $i <10; $i++) {
$wholename[]=$fname[$i]." ".$lname[$i];
}
return $wholename;
}
function printTable($firstname,$lastname){
echo"<table border='1'>";
for($i=0;$i<10;$i++){
echo"<tr><td>".$firstname[i]." ".$lastname[i]."</td></tr>";
}
echo "</table>";
}
printTable($firstname,$lastname);
?>
Something like this:
<?php
$firstname=
array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");
$lastname=
array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");
function fullname($index){
return $firstname[$index] . " " . $lastname[$index];
}
function printTable(){
echo"<table border='1'>";
for($i=0;$i<10;$i++){
echo"<tr><td>".fullname($i)."</td></tr>";
}
echo "</table>";
}
printTable();
?>
For the row colouring see: http://www.w3.org/Style/Examples/007/evenodd
If you don't want to use CSS for alternating row colours, you can use the remainder/mod operator % on the loop variable. $i % 2 means the remainder when $i is divided by 2 (ie, alternating 0,1,0,1,... as $i is incremented).
if (($i % 2) == 0) {echo "<tr bgcolor=#ff0000>"} else {echo "<tr bgcolor=#00ff00>"}

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

Categories