I am newbie in php.
I have one table in mysql (example)
id id_pro name
1 2 budi
2 1 adi
3 1 steve
4 1 jono
5 2 galang
I would like to print like this
id_pro name
1 adi, steve, jono
2 budi, galang
I have made,but look like this. (Please help me)
id_pro name
1 adi
1 steve
1 jono
2 budi
2 galang
<?php
$a = mysql_connect("localhost","root","admin");
mysql_select_db("aa");
$result = mysql_query("select * from member");
echo '<table>
<tr><th>id_pro</th><th>name</th></tr>';
while($data = mysql_fetch_array($result))
{
echo '<tr>';
echo '<td> '. $data["id_pro"] .'</td>';
echo '<td> '. $data["name"] .'</td>';
echo '</tr>';
}
?>
<?php
$result = array();
$data = array(array("id_pro"=>1,"name"=>"adi"),array("id_pro"=>2,"name"=>"budi"),array("id_pro"=>1,"name"=>"steve"));
foreach($data as $value){
$result[$value["id_pro"]][] = $value["name"];
}
foreach($result as $key => $value){
echo $key . "----" . implode("," , $value);
echo "\n";
}
?>
or you can change your sql like this :
select id_pro,group_concat(name) from member group by id_pro;
Related
I have an script for getting a table from a DB which is written in PHP.
I am trying to add name for each column to be in the first row:
A part of the Code is:
$rows = [];
foreach (range(1, 4) as $row) {
$rows[$row] = "";
}
$rows["Name"] = $order->user->aFirstName;
$rows["Last Name"] = $alumn->aLastName;
$rows["Age"] = $alumn->aAge;
$rows["Gender"] = $alumn->aGender;
$string = "";
foreach ($rows as $r) {
$string .= $r . "\t";
}
what I want to get is
1 | Name | Last Name | Age | Gender
2 | John | Des | 45 | Male.
What I get now is the data in 1st row.
1 | John | Des | 45 | Male.
Any suggestion? Thanks
You can create a new first element in $rows using https://www.php.net/manual/de/function.array-unshift.php
$labels = ["Name" => "NameLabel", "Last Name" => "Last NameLabel" ...];
array_unshift($rows, $labels);
So the first element of the $rows array are the labels. Now when the table is generated is will display the labels at the top.
You are loading the arrays incorrectly.
I assume you dont want to get the column names from the meta data available to you, and are happy to add the column names manually, if not let me know
$rows = [];
// add labels
$rows[] = ["Name", "Last Name", "Age", "Gender"];
#$rows[] = [$order->user->aFirstName, $alumn->aLastName, $alumn->aAge, $alumn->aGender];
// I dont have your data, so this is to simulate the above line
$rows[] = ['John', 'Des', 45, 'Male'];
$string = '';
foreach ($rows as $i => $row) {
$n = $i+1;
$string .= "$n\t";
foreach ($row as $col){
$string .= $col . "\t";
}
$string .= '<br>'. PHP_EOL;
}
print_r($string);
RESULTS, as you can see a Tab is not really enough to correctly format the table
1 Name Last Name Age Gender <br>
2 John Des 45 Male <br>
I have the following php array and I am trying to print a table with 4 columns. All is OK until the array has 4, 8, 12 and etc. keys /values but when array has length that can not be divided by 4 becomes the problem. Here is the sample array:
$newarray =array(
"make"=> "Ford" ,
"model"=> "S-MAX" ,
"model_year"=> "2009" ,
"made"=> "2010-01-01" ,
"manufacturer"=> "Ford Werke AG" ,
"manufacturer_address"=> "Koeln-Niehl, Germany" ,
"body"=> "Sedan/Saloon" ,
"engine_power_kw"=> "142" ,
"engine_displacement_ccm"=> "2000" ,
"engine_full"=> "2.0L Duratorq-TDCi (143PS) - DW"
);
and the code that prints the table:
$rama_result.='<table class="table w100 customtable">';
$i=1;
foreach($newarray as $key=>$value){
$rama_result1.= '<th>'.$key.'</th>';
$rama_result2.= '<td>'.$value.'</td>';
if($i % 4 == 0){
$rama_result.='</tr><tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr><tr>';
$rama_result1 = '';$rama_result2 = '';
}
$i++;
}
$rama_result.='</tr></table>';
Can you please help and show me the way to print the missing 2 in the last row so the code to work correct. Thank you for your help
The code above prints this table
<table class="table w100 customtable"><tbody>
<tr><th>make</th><th>model</th><th>model_year</th><th>made</th></tr>
<tr><td>Ford</td><td>S-MAX</td><td>2009</td><td>2010-01-01</td></tr><tr></tr>
<tr><th>manufacturer</th><th>manufacturer_address</th><th>body</th><th>engine_power_kw</th></tr>
<tr><td>Ford Werke AG</td><td>Koeln-Niehl, Germany</td><td>Sedan/Saloon</td> <td>142</td></tr>
<tr></tr></tbody></table>
<table class="table w100 customtable"><tbody>
<tr><th>make</th><th>model</th><th>model_year</th><th>made</th></tr>
<tr><td>Ford</td><td>S-MAX</td><td>2009</td><td>2010-01-01</td></tr><tr></tr>
<tr><th>manufacturer</th><th>manufacturer_address</th><th>body</th><th>engine_power_kw</th></tr>
<tr><td>Ford Werke AG</td><td>Koeln-Niehl, Germany</td><td>Sedan/Saloon</td> <td>142</td></tr>
<tr></tr></tbody></table>
Instead of looping each value use array_chunk to split the array then implode the headers and values.
$arr = array_chunk($newarray, 4, true);
echo "<table>\n";
foreach($arr as $sub){
echo "<tr><th>" . implode("</th><th>", array_keys($sub)) . implode("</th><th>", array_slice([" ", " ", " "],0 , 4-count($sub))) . "</th></tr>\n";
echo "<tr><td>" . implode("</td><td>", $sub) . implode("</td><td>", array_slice([" ", " ", " "],0 , 5-count($sub))) ."</td></tr>\n";
}
echo "</table>";
Output:
<table>
<tr><th>make</th><th>model</th><th>model_year</th><th>made</th></tr>
<tr><td>Ford</td><td>S-MAX</td><td>2009</td><td>2010-01-01 </td></tr>
<tr><th>manufacturer</th><th>manufacturer_address</th><th>body</th><th>engine_power_kw</th></tr>
<tr><td>Ford Werke AG</td><td>Koeln-Niehl, Germany</td><td>Sedan/Saloon</td><td>142 </td></tr>
<tr><th>engine_displacement_ccm</th><th>engine_full </th><th> </th></tr>
<tr><td>2000</td><td>2.0L Duratorq-TDCi (143PS) - DW </td><td> </td><td> </td></tr>
</table>
https://3v4l.org/TrCnM
Edited to include the empty cells.
You could just extend the array to have a multiple of 4 elements before you start:
for ($c = count($newarray); $c % 4 != 0; $c++) {
$newarray[str_repeat("\n", $c % 4)] = '';
}
$rama_result.='<table class="table w100 customtable">';
$i=1;
// ...
Demo on 3v4l.org
After the loop, you could check that there is something still in $rama_result1 - which would mean there is data left to be added into the table. This code pads the existing content with enough empty cells to make it up to the 4 columns (you can tweak the content if desired in the str_repeat() calls).
if ( $rama_result1 != '' ) {
$i--;
$rama_result1 .= str_repeat("<th />", 4-($i%4));
$rama_result2 .= str_repeat("<td />", 4-($i%4));
$rama_result.='<tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr>';
}
Also (as Nick pointed out) there are extra <tr> tags in various places. I've updated a few other parts of the code to try and tidy up the generated HTML...
$i=1;
foreach($newarray as $key=>$value){
$rama_result1.= '<th>'.$key.'</th>';
$rama_result2.= '<td>'.$value.'</td>';
if($i % 4 == 0){
$rama_result.='<tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr>'.PHP_EOL;
$rama_result1 = '';
$rama_result2 = '';
}
$i++;
}
if ( $rama_result1 != '' ) {
$i--;
echo ($i%4).PHP_EOL;
$rama_result1 .= str_repeat("<th />", 4-($i%4));
$rama_result2 .= str_repeat("<td />", 4-($i%4));
$rama_result.='<tr>'.$rama_result1.'</tr><tr>'.$rama_result2.'</tr>'.PHP_EOL;
}
$rama_result.='</table>';
I'm currently working on a small website where my colleagues can see their work times.
My "rooster" table looks like this:
rooster_id int(2) Auto_increment primary key.
personeel_id int(2) //personeel means staff in the Dutch language
(I'm using inner join to get the person's name).
dag varchar(10) //dag means day.
start varchar(5) //start is the time when the employee has to start
working.
eind varchar(5) //eind means end.
datum date
weeknummer int(2) //weeknummer means weeknumber.
Display:
---------------------------------------------------------------------
|rooster_id|personeel_id|dag |start|eind |datum |weeknummer|
|1 |1 |Tuesday |12:00|21:00|2016-05-10|19 |
|1 |1 |Wednesday|15:00|21:00|2016-05-11|19 |
|1 |2 |Monday |08:00|18:30|2016-05-10|19 |
---------------------------------------------------------------------
My php code above HTML tag:
include_once 'config.php';
$people = "SELECT DISTINCT * FROM personeel INNER JOIN rooster ON rooster.personeel_id = personeel.id";
$result = mysql_query($people);
My php code inside the table tag:
<table cellpadding="1" width="100%" cellspacing="1" class="box-inhoud">
<?php
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['naam']."</td>";
if($row['dag'] === "maandag"){
echo "<td class='td-midden'>".$row['start']." - ".$row['eind']."</td>";
} else {
echo "<td class='td-midden'>Vrij</td>";
}
if($row['dag'] === "dinsdag"){
echo "<td class='td-midden'>".$row['start']." - ".$row['eind']."</td>";
} else {
echo "<td class='td-midden'>Vrij</td>";
}
if($row['dag'] === "woensdag"){
echo "<td class='td-midden'>".$row['start']." - ".$row['eind']."</td>";
} else {
echo "<td class='td-midden'>Vrij</td>";
}
if($row['dag'] === "donderdag"){
echo "<td class='td-midden'>".$row['start']." - ".$row['eind']."</td>";
} else {
echo "<td class='td-midden'>Vrij</td>";
}
if($row['dag'] === "vrijdag"){
echo "<td class='td-midden'>".$row['start']." - ".$row['eind']."</td>";
} else {
echo "<td class='td-midden'>Vrij</td>";
}
if($row['dag'] === "zaterdag"){
echo "<td class='td-midden'>".$row['start']." - ".$row['eind']."</td>";
} else {
echo "<td class='td-midden'>Vrij</td>";
}
if($row['dag'] === "zondag"){
if($row['start'] === "00:00:00"){
echo "<td class='td-midden'>Feestdag</td>";
} else {
echo "<td class='td-midden'>".$row['start']." - ".$row['eind']."</td>";
}
} else {
echo "<td class='td-midden'>Vrij</td>";
}
echo "</tr>";
}
?>
</table>
This displays the data like this:
------------------------------------------------------
|Employee's|Monday |Tuesday |Wednesday |
|Tom |Vrij |12:00 - 21:00|Vrij |
|Tom |Vrij |Vrij |15:00 - 21:00|
|Jack |08:00 - 18:30|Vrij |Vrij |
------------------------------------------------------
It also displays Thursday, Friday, Saturday, Sunday but I didn't want to write all of the days here on stackoverflow since those will have "vrij" as value.
But the thing is, I want to have it like this:
------------------------------------------------------
|Employee's|Monday |Tuesday |Wednesday |
|Tom |Vrij |12:00 - 21:00|15:00 - 21:00|
|Jack |08:00 - 18:30|Vrij |Vrij |
------------------------------------------------------
So every employee does only have 1 row with all their times listed in it.
I'm new on this website so I hope I explained everything good, so you guys can easily help me.
And yes I know, I'm using MySQL because I want to keep it simple and I have never worked with MySQLi nor PDO.
Here we go entire example:
<?php
$con = mysqli_connect('localhost', 'root', '', 'test') or die(mysqli_error($con));
$query = "SELECT * FROM personeel INNER JOIN rooster ON rooster.personeel_id = personeel.id";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
if (mysqli_num_rows($result) > 0) {
$arr = array();
$nam = array();
$day = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
while ($row = mysqli_fetch_assoc($result)) {
$nam[$row['id']] = $row['naam'];
$arr[$row['id']][$row['dag']] = $row['start'] . ' - ' . $row['eind'];
}
echo '<table border="1">';
echo '<tr>';
echo '<td>Employees</td>';
foreach($day as $d){
echo '<td>'.$d.'</td>';
}
echo '</tr>';
foreach ($nam as $k=>$n){
echo '<tr>';
echo '<td>'.$n.'</td>';
foreach ($day as $d){
if(isset($arr[$k][$d])){
echo '<td>'.$arr[$k][$d].'</td>';
}else{
echo '<td>Virj</td>';
}
}
echo '</tr>';
}
echo '</table>';
}
?>
Output is:
Some details:
$nam array stores all fetched names from personeel together with his id relation.
Array
(
[1] => Tom
[2] => Jack
)
$arr is main array which contains relation between personeel id and his data:
Array
(
[1] => Array
(
[Tuesday] => 12:00 - 21:00
[Wednesday] => 15:00 - 21:00
)
[2] => Array
(
[Monday] => 08:00 - 18:30
)
)
$day is static array with week days.
Walking trough both $nam and $arr arrays gives you desired table without any duplicates. In addition provided solution uses mysqli_* functions, so you can see how to use them.
Hope this will help you to solve your problem. :)
im in serach for a generic piece of code that uses and array
$arr[$key1][$key2] = $value;
output should be like this where "SUM" is not part of the array.
| 1st key2 | 2nd key2 | 3rd key2 | SUM
1st key1 | 10 | 10 | 10 | 30
2nd key1 | 10 | 10 | 10 | 30
3rd key1 | 10 | 10 | 10 | 30
SUM | 30 | 30 | 30 | 90
so i startet an output to see how far i get:
echo '<table width="100%"><thead>';
foreach($arr as $linekey => $line)
{
echo '<tr>';
echo '<th align="center">';
echo '</th>';
foreach($line as $key => $value)
{
echo '<th align="center">';
echo $key;
echo '</th>';
}
echo '<th align="center">';
echo 'SUM'; //adding the SUM column
echo '</th>';
echo '</tr>';
break;
}
echo '</thead><tbody>';
foreach($arr as $key1 => $value1)
{ echo '<tr>';
echo'<td>'.$key1.'</td>';
$sumRow = 0; //reset sumRow
foreach($arr[$key1] as $key2 => $value2)
{
echo'<td>'.round($arr[$key1][$key2],0).'</td>';
$sumRow += $arr[$key1][$key2]; //summing up rows
$sumAll += $arr[$key1][$key2]; //summing up everything
$sumCol += $arr[$key1][$key2]; //where should be this?
}
echo'<td>'.round($sumRow,0).'</td>'; //echo $sumRow
echo '</tr>';
}
echo '</tbody></table>';
this alaredy works but im not sure where to sum the columns
You should use an array $sumCol to gather columns sums:
$sumCol[$key2] += $arr[$key1][$key2];
It size should be as number of columns.
You cannot do it in one loop without an array because you loop over columns index internally, so you could gather only sumRow in one temporary variable (without array).
Then, at the end:
echo '<tr><td>SUM</td>';
foreach($sumCol as $key2 => $value2)
{
echo'<td>'.round($sumCol[$key2],0).'</td>'; //echo $sumCol
}
echo '</tr>';
echo '</tbody></table>';
The other way is to define the second loop where you iterate first over columns and at second, internally, over rows.
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