Add multiple arrays in single table - php

<table border="2">
<?php
foreach($array1 as $value)
{
echo '<tr><td>';
echo $value;
echo '</td></tr>';
}
?>
</table>
I have more array: array2,array3.
The above code only executes values of array1 but I want all the values of all array in the same table in separate columns!
array1 | array2 | array3
------------------------
| |
| |
| |
| |
I want something like this...
I tried modifying the code but no idea how to do it correctly.
$data = mysql_query(" SELECT * FROM user_pokemon_db WHERE user_id = '".$id."' ");
while($rows = mysql_fetch_assoc($data)) {
$db_id = $rows['id'];
$array[] = $db_id;
$level = $rows['level'];
$array1[] = $level;
$exp = $rows['exp'];
$array2[] = $exp;
$pkmn_id = $rows['pkmn_id'];
$data1 = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$pkmn_id."' ");
while($rows = mysql_fetch_assoc($data1)) {
$poke = $rows['path']; $array3[] = $poke;
}
}
The above code fetches data from database and adds it to different arrays!

When you create your array, you don't specify keys, so they are generated automaticaly. So you can work on keys for your for loop instead of using a foreach in values:
We can see in your code that $array3 is longuer than the others. So we will base on it:
foreach($array3 as $key => $value)
{
if (isset($array1[$key])){
echo '<tr><td>'.$array1[$key].'</td>';
}else{
echo '<tr><td></td>';
}
if (isset($array2[$key])){
echo '<td>'.$array2[$key].'</td>';
}else{
echo '<td></td>';
}
echo '<td>'.$array3[$key].'</td></tr>';
}
It should work

try making a function that calls itself in the end. not sure if I got the syntax right here, but this should work.
$i = 0;
function test($i){
if($i < ar1.lenght && $i < ar2.lenght && $i< ar3.lenght){
echo "<tr><td>";
echo ar1[$i];
echo "</td><td>";
echo ar2[$i];
echo "</td><td>";
echo ar3[$i];
echo "</td></tr>";
$i++;
//calls itself with an incremented $i
test($i);
}//else do nothing.
}
--edit forgot some tags

Related

How to get id while in a loop in php

Wanted to get 2 values id and name but im confuse how get it, i wanted to show the id in the link. heres the sample code.
echo "<table width=\"100%\" border=\"1\" cellpadding=\"5\" cellspacing=\"2\" bordercolor=\"#FFFFFF\">";
$count = 1;
$id=$_GET['id'];
$col1 = $col2 = array();
$rowcount = round(mysqli_num_rows($nquery) / 2);
while($crow = mysqli_fetch_assoc($nquery)) {
if($count > $rowcount) $col2[] = $crow['title'];
else $col1[] = $crow['title'];
$count++;
}
$counter = 0; // Arrays start with 0
foreach($col1 as $crow) { // $col1 will always be >= $col2
$row2 = (isset($col2[$counter])) ? $col2[$counter] : "";
echo "<tr><td><a href='index.php?page=".$id."'>" . $crow . "</td><td>" . $row2 . "</td></tr>";
$counter++;
}
echo "</table>";
?>`
id wont show up on the link. Hope someone can help. Thanks
You're trying to get $id values from the query string (that's what the $_GET superglobal is) and not from the database.
If both elements (ID and name) are coming from the same database query, you may try something like this:
$crow = mysqli_fetch_assoc($nquery);
foreach ($crow as $row)
{
echo $row['id'].' is the ID and '.$row['title'].' is the title';
}
if you remain within the foreach loop, you can use $row['id'] and $row['title'] to build the table element and link you're trying to obtain.

How to rewrite complex mysql_* SELECT as PDO?

I'm upgrading all my mysql_* to PDO. I can handle simple SELECTs and INSERTs. But I have one complex SELECT using nested loops that I am making a dog's dinner of. I'll post the mysql_* code, which outputs a two-column table with total registrations at A1 level in the first column and total registrations at A1 level who have paid in brackets in the second column.
-------------------------
Smithsville : A1 | |
10 | (7) |
-------------------------
Grange : A1 | |
4 | (4) |
-------------------------
Beau Ridge : A1 | |
23 | (16)|
-------------------------
Jonesboro : A1 | |
9 | (9) |
-------------------------
Lexing : A1 | |
3 | (1) |
-------------------------
In the full application further tables are genertated across the page for the other levels.
$levels = array('A1', 'A2', 'B1', 'B2');
$centres = array('Smithsville', 'Grange', 'Plateau Ridge', 'Jonesboro', 'Lexing');
for ($j = 0; $j < 1; $j++) /* Does not loop; selects only A1 in queries below*/
{
for ($k=0; $k<5; $k++) /* Cycles through the centres */
{
$show_count = mysql_query("SELECT COUNT(Centre)
FROM exam
WHERE exam.Centre='".$centres[$k]."'
AND exam.Level='".$levels[$j]."'");
$show_paid = mysql_query("SELECT COUNT(Centre)
FROM exam
JOIN personal
ON exam.P_ID=personal.P_ID
WHERE personal.Paid='1'
AND exam.Centre='".$centres[$k]."'
AND exam.Level='".$levels[$j]."'");
$result_rows = mysql_num_rows($show_count);
$result_rows2 = mysql_num_rows($show_paid);
if ($result_rows == 0)
{ echo 'No registrations';}
if ($result_rows2 == 0)
{ echo 'No payments';}
echo '<table class="Font3White">
<tr class="Title">
<td class="width8">'.$centres[$k].' : '.$levels[$j].'</td>
<tr>';
while (($row = mysql_fetch_row($show_count)) && ($row2 = mysql_fetch_row($show_paid)))
{
foreach ($row as $key => $value)
{
echo '<td>';
echo $value;
echo '</td>';
}
foreach ($row2 as $key2 => $value2)
{
echo '<td> (';
echo $value2;
echo ')</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
My PDO attempt is
for ($j = 0; $j < 1; $j++) /* Does not loop; selects only A1 */
{
for ($k=0; $k<5; $k++) /* Cycles through the centres */
{
/*//////////////////////////*/
/* Prepares statements */
/*//////////////////////////*/
$stmt1 = $db->query("SELECT COUNT(Centre)
FROM exam
WHERE exam.Centre=:centre
AND exam.Level=:level");
$stmt2 = $db->query("SELECT COUNT(Centre)
FROM exam
JOIN personal
ON exam.P_ID=personal.P_ID
WHERE personal.Paid='1'
AND exam.Centre=:centre
AND exam.Level=:level");
/*/////////////////////*/
/* Binds parameters */
/*/////////////////////*/
$stmt1->bindParam(':centre', $centre, PDO::PARAM_STR);
$stmt1->bindParam(':level', $level, PDO::PARAM_STR);
$stmt2->bindParam(':centre', $centre, PDO::PARAM_STR);
$stmt2->bindParam(':level', $level, PDO::PARAM_STR);
/*//////////////////////////*/
/* Executes statements */
/*//////////////////////////*/
$stmt1->execute(array($centre, $level));
$stmt2->execute(array($centre, $level));
echo '<table class="Font3White">
<tr class="Title">
<td class="width8">'.$centres[$k].' > '.$levels[$j].'</td>
<tr>';
while (($row = $stmt1->fetch(PDO::FETCH_ASSOC)) && ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)))
{
foreach ($row as $key => $value)
{
echo '<td>';
echo $value;
echo '</td>';
}
foreach ($row2 as $key2 => $value2)
{
echo '<td> (';
echo $value2;
echo ')</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
I know this is terrible but I hope it can be worked with.
I know it's wrong to make you the dirty work, but that's it.
I made some changes to your code, so compare mine with yours.
Hope it helps you.
$levels = array('A1', 'A2', 'B1', 'B2');
$centres = array('Smithsville', 'Grange', 'Plateau Ridge', 'Jonesboro', 'Lexing');
foreach ($levels as $level) {
foreach ($centres as $centre) {
// As you said, PREPARE
$stmt1 = $db->prepare("SELECT COUNT(Centre)
FROM exam
WHERE exam.Centre=:centre
AND exam.Level=:level");
$stmt2 = $db->prepare("SELECT COUNT(Centre)
FROM exam
JOIN personal
ON exam.P_ID=personal.P_ID
WHERE personal.Paid='1'
AND exam.Centre=:centre
AND exam.Level=:level");
$stmt1->bindParam(':centre', $centre, PDO::PARAM_STR);
$stmt1->bindParam(':level', $level, PDO::PARAM_STR);
$stmt2->bindParam(':centre', $centre, PDO::PARAM_STR);
$stmt2->bindParam(':level', $level, PDO::PARAM_STR);
//You don't need to pass parameters here just on PDOStatement::bindParam
$stmt1->execute();
$stmt2->execute();
echo '<table class="Font3White">
<tr class="Title">
<td class="width8">' . $centre . ' > ' . $level . '</td>
<tr>';
// Fetch stuffs
$row = $stmt1->fetch(PDO::FETCH_ASSOC);
$row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
// Don't use while with PDOStatement::fetch, use fetchAll then foreach it.
if ($row && $row2) {
foreach ($row as $key /* <= Do you need it? */ => $value) {
echo '<td>';
echo $value;
echo '</td>';
}
foreach ($row2 as $key2 /* <= Do you need it? */ => $value2) {
echo '<td> (';
echo $value2;
echo ')</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
Can you show us how you set $centre and $level variables? Maybe they are arrays, not strings? If they are - you may have to create new variable and assign value from array to it. Like this:
$value_to_bind = $centres[$k];
Execute does not need parameters if you used bindParam() before.
I never tried to run 2 queries with same parameter names and same variables binded to them. Maybe this is a problem?

unknown columns, column names, and rows into HTML table

I'm trying to display all the information in a msSQL table in an HTML table and have up with something that is not so great.
<table border="1">
<?
echo "<tr>";
for ($i = 0; $i < mssql_num_fields($result); ++$i){
echo "<th>" .$column_names[$i] . "</th>";
}
echo "</tr>";
$num_rows = mssql_num_rows($result);
for ($i = 0; $i < $num_rows; ++$i){
echo "<tr>";
foreach ($column_names as $key => $val){
$result_row = mssql_query("SELECT * FROM username WHERE id = '$i'");
$row = mssql_fetch_assoc($result_row);
echo "<td>";
echo $row[$val];
echo "</td>";
}
echo "</td>";
}
?>
</table>
This works. The first part prints out the column names successfully, but as for the rest:
1) I think it is sort of cumbersome to make a query for every time through the loop
2) it doesn't really work because the ids of the rows go much higher than the number of rows in the table, as some ids aren't used.
It seems like I should be able just make one query and pull everything from the database at one go, then build my HTML table from that, but I can't figure out how to access it row by row where I could go $row[next row][shifted value from $column_names. How can improve this query?
function table_cell($item, $header=false) {
if (!$item) return '';
$elemname = ($header) ? 'th' : 'td';
$escitem = htmlspecialchars($item, ENT_NOQUOTES, 'UTF-8');
return "<{$elemname}>{$escitem}</{$elemname}>";
}
function table_header_cell($item) {
return table_cell($item, true);
}
function table_row($items, $header=false) {
$func = ($header) ? 'table_header_cell' : 'table_cell';
return "<tr>\n\t".implode("\n\t", array_map($func, $items))."\n</tr>\n";
}
function echo_result_as_table($result) {
if ($result && $row = mssql_fetch_assoc($result)) {
$columnnames = array_keys($row);
echo "<table>\n", table_row($columnnames, true), "\n";
do {
echo table_row($row), "\n";
} while ($row = mssql_fetch_assoc($result));
echo "</table>\n";
}
}
$result = mssql_query("SELECT * FROM username");
echo_result_as_table($result);
if ($result) mssql_free_result($result);
If you have an array of associative arrays instead of a raw mssql result handle, you can use a function like this to produce a table string:
function array_to_table($arrayofassoc) {
if (!$arrayofassoc) return '';
$tablestr = '<table>';
$tablestr .= table_row(array_keys($arrayofassoc[0]), true);
$tablestr .= implode('', array_map('table_row', $arrayofassoc));
$tablestr .= '</table>';
return $tablestr;
}
try this:
while($row = mysql_fetch_results($result)){
echo '<td>'.$row['column_name'].'</td>';
}
with 'column_name' being the name of the column in mysql.
but some will say..."wait, but PDO"

Display php nested array results continuously in two column table

I have a nested array grouping three other arrays: $online, $busy and $offline, in order to display results in this exactly order.
$conteudo = array($online, $ocupado, $offline);
The desired result would be a table in two columns to display results in continuous flow like this:
online1 | online2
online3 | busy1
busy2 | offline1
offline2| offline3
offline4|
I've been trying lots of foreach loops and playing around changing the html tags, but the closest I can arrive of the desired result is this:
<table width='100%' cellpadding='5' border="1">
<?php
$i = 1; //contador de colunas
$max_colunas = 2; // numero de colunas
foreach ($conteudo as $row) {
echo "<tr>";
foreach ($row as $col) {
foreach ($col as $cell) {
if ($i == 1) {
echo "<td>" . $cell . "</td>";
} elseif ($i == $max_colunas){
echo "<td>" . $cell . "</td></tr>";
$i = 0;
} else {
echo "<td>" . $cell . "</td>";
}
$i++;
}
}
echo "</tr>";
}
This code will output a table like this:
onine1 | online2 |online3
busy1 | busy2 |
offline1|offline2 |offline3|offline4
I can't find out why it ignores completely $max_colunas, seems like it prints all the elements inside the array in row.
If I remove lines:
echo "<tr>";
echo "</tr>";
from beginning and end of foreach it will output all in a row like this:
onine1 | online2 |online3 | busy1 | busy2 |offline1|offline2 |offline3|offline4
Any suggestions to get the desired output format will be so appreciated.
Edited on 17/01:
This is how I'm getting the arrays from:
//group people
$online = array(); //group online
$ocupado = array(); //group ocupado
$offline = array(); //group offline
//select people to group
$atendentes = mysql_query("SELECT nome FROM atendentes ORDER BY nome") or die(mysql_error());
$atendentedb = array();
//put selected people in array
while ($row = mysql_fetch_assoc($atendentes)) {
$atendentedb[] = array('nome' => $row["nome"], 'online' => false);
}
//take people online now and check in selected people
$names = modWhosonlineCustom::getOnlineUserNames();
foreach ($names as $name):
//foreach ($atendentedb as $atendente):
for($i = 0; $i < count($atendentedb); $i++):
$att = strtolower($name->username);
if ($atendentedb[$i]['nome'] == $att):
$atendentedb[$i]['online'] = true;
break;
endif;
endfor;
endforeach;
//check each selected people
foreach ($atendentedb as $atendente) :
//save temporary data
$online_ = $atendente['online'];
$nome_ = $atendente['nome'];
//if selected people online
if ($online_) :
//take status to show
$status = mysql_query("SELECT status FROM atendentes WHERE nome = '$nome_' LIMIT 1") or die(mysql_error());
while ($row = mysql_fetch_assoc($status)):
$statusdb = $row["status"];
endwhile;
//verify and save deppending on status
switch ($statusdb):
//if online
case "disponivel":
$descricao = mysql_query("SELECT hp_online FROM atendentes WHERE nome = '$nome_' LIMIT 1") or die(mysql_error());
while ($row = mysql_fetch_assoc($descricao)):
$online[] = array('info'=>$row['hp_online']);
endwhile;
break;
//if busy
case "ocupado":
$descricao = mysql_query("SELECT hp_busy FROM atendentes WHERE nome = '$nome_' LIMIT 1") or die(mysql_error());
while ($row = mysql_fetch_assoc($descricao)):
$ocupado[] = array('info'=>$row['hp_busy']);
endwhile;
break;
endswitch;
//if offline
else:
$descricao = mysql_query("SELECT hp_offline, horario FROM atendentes WHERE nome = '$nome_' LIMIT 1") or die(mysql_error());
while ($row = mysql_fetch_assoc($descricao)):
$offline[] = array('info'=>$row['hp_offline'], 'horario'=>$row['horario']);
endwhile;
endif;
endforeach;
EDITED
So after following help instructions from DaveRandom I got to this code, which is really a drop away from the right format, except for the "mysterious" behaviour with results coming from array $offline, that are displaying all in "block" (all cells in a row, or all cells in a column) while the other arrays are displaying perfectly(??).
//group people
$online = $ocupado = $offline = array();
//select people to group
$query = "SELECT nome, status, hp_online, hp_busy, hp_offline, horario
FROM atendentes
ORDER BY nome";
$atendentes = mysql_query($query) or die(mysql_error());
$atendentedb = array();
// put selected people in array
while ($row = mysql_fetch_assoc($atendentes)) {
$atendentedb[strtolower($row['nome'])] = array_merge($row, array('online' => FALSE));
}
//take people online now and check in selected people
$names = modWhosonlineCustom::getOnlineUserNames();
foreach ($names as $name) {
$uname = strtolower($name->username);
if (isset($atendentedb[$uname])) $atendentedb[$uname]['online'] = TRUE;
}
//check each selected people
foreach ($atendentedb as $name => $atendente) {
//if selected people online
if ($atendente['online']) {
//verify and save deppending on status
switch ($atendente['status']) {
//if online
case 'disponivel':
$atendentedb[$name]['info'] = $online[] = $atendente['hp_online'];
break;
//if busy
case 'ocupado':
$atendentedb[$name]['info'] = $ocupado[] = $atendente['hp_busy'];
break;
}
//if offline
} else {
$atendentedb[$name]['info'] = $offline[] = $atendente['hp_offline'];
$atendentedb[$name]['info'] = $offline[] = $atendente['horario'];
}
}
//*******Display Results
$conteudo = array_merge($online, $ocupado, $offline);
$max_colunas = 2; // numero de colunas
// Start the table
echo '<table width="100%" cellpadding="5" border="1">'."\n";
// Loop all the objects
for ($i = 0, $j = 0; isset($conteudo[$i]); $i++) {
if ($j == 0) {
// Output the beginning of a row
echo " <tr>\n";
}
// Always output a data cell
echo " <td>$conteudo[$i]</td>\n";
if (++$j >= $max_colunas) {
// Output the end of a row and reset the cell counter
echo " </tr>\n";
$j = 0;
}
}
if ($j) {
// We may end up with an incomplete row at the end, so pad it with empty cells
// and close the row
while ($j++ < $max_colunas) {
echo " <td></td>\n";
}
echo " </tr>\n";
}
// Close the table
echo "</table>";
I would say that the first thing to do here is to "flatten" the array - having the multiple dimensions makes this a lot more complicated than it needs to be. So rather than creating $conteudo like this:
$conteudo = array($online, $ocupado, $offline);
...do this instead:
$conteudo = array_merge($online, $ocupado, $offline);
Then you can do this:
$max_colunas = 2; // numero de colunas
// Start the table
echo '<table width="100%" cellpadding="5" border="1">'."\n";
// Loop all the objects
for ($i = 0, $j = 0; isset($conteudo[$i]); $i++) {
if ($j == 0) {
// Output the beginning of a row
echo " <tr>\n";
}
// Always output a data cell
echo " <td>$conteudo[$i]</td>\n";
if (++$j >= $max_colunas) {
// Output the end of a row and reset the cell counter
echo " </tr>\n";
$j = 0;
}
}
if ($j) {
// We may end up with an incomplete row at the end, so pad it with empty cells
// and close the row
while ($j++ < $max_colunas) {
echo " <td></td>\n";
}
echo " </tr>\n";
}
// Close the table
echo "</table>";
See it working
EDIT
Try this code for generating your arrays. Note that the structure of your output arrays has been altered to fit my code sample above - if you use this data anywhere else in you script, you will need to modify that code as well. I have modified this so that there is only one database query, which would seem to be all that is required. I have also modified it so that the $atendentedb holds all the user data, including the status and info keys, and all rows contain a horario key.
Because of the fact that your input arrays originally contained more data than the ones created by this code will, the code may need further modification - but try this out and see how you get on.
//group people
$online = $ocupado = $offline = array();
//select people to group
$query = "SELECT nome, status, hp_online, hp_busy, hp_offline, horario
FROM atendentes
ORDER BY nome";
$atendentes = mysql_query($query) or die(mysql_error());
$atendentedb = array();
// put selected people in array
while ($row = mysql_fetch_assoc($atendentes)) {
$atendentedb[strtolower($row['nome'])] = array_merge($row, array('online' => FALSE));
}
//take people online now and check in selected people
$names = modWhosonlineCustom::getOnlineUserNames();
foreach ($names as $name) {
$uname = strtolower($name->username);
if (isset($atendentedb[$uname])) $atendentedb[$uname]['online'] = TRUE;
}
//check each selected people
foreach ($atendentedb as $name => $atendente) {
//if selected people online
if ($atendente['online']) {
//verify and save deppending on status
switch ($atendente['status']) {
//if online
case 'disponivel':
$atendentedb[$name]['info'] = $online[] = $atendente['hp_online'];
break;
//if busy
case 'ocupado':
$atendentedb[$name]['info'] = $ocupado[] = $atendente['hp_busy'];
break;
}
//if offline
} else {
$atendentedb[$name]['info'] = $offline[] = $atendente['hp_offline'].' '.$atendente['horario'];
}
}
I think you should update counter inside
foreach ($col as $cell) { } so it will count elements of the inner arrays and also move decalration of <tr> there.
if (!is_int($i/2)) { print '<tr><td>' }

Create an HTML table like this one

i posted a question a while ago and i got my answer but now i kind of want a followup to this problem so i have a table like the one in the picture but i want to add total to each row or in fact a group how can i do that.
This is the php code to create this table how to edit it to add the total.
$sql = mysql_query(
"SELECT s.login AS 'from', r.login AS 'to',COUNT(*) as'message_count'
FROM messages AS m,groups AS s,groups AS r
WHERE m.Group_ID = s.id
AND m.To_Group_ID = r.id
AND m.Simulation_ID = ".$_SESSION['sim_id']."
AND s.kind_of_user NOT IN (3,1)
AND r.kind_of_user NOT IN (3,1)
AND m.Group_ID IN
(SELECT Group_ID FROM simulationgroups
WHERE Simulation_ID = ".$_SESSION['sim_id'].")
AND m.To_Group_ID IN
(SELECT Group_ID FROM simulationgroups
WHERE Simulation_ID = ".$_SESSION['sim_id'].")
GROUP BY m.Group_ID, m.To_Group_ID
ORDER BY s.id DESC"
) or die (mysql_error());
$data = array();
while($row = mysql_fetch_assoc($sql))
{
$data[$row['to']][$row['from']] += $row['message_count'];
}
// Print headers
$columns = array_keys($data);
echo "<table class='msg_dynamics' cellspacing=0
cellpadding=0 border=1px><tr><th><<</th>";
foreach($columns as $_column)
{
echo "<th width='10%'>{$_column}</th>";
}
echo "<th width='10%'>total</th>";
echo "</tr>";
// Print data
foreach($data as $_row_name => $_row_data)
{
// Add the dash (-) for empty cells
$_row_data[$_row_name] = '-';
echo "<tr><td width='10%'>{$_row_name}";
foreach($columns as $_col_name)
{
echo "<td>{$_row_data[$_col_name]}</td>";
}
echo "</td></tr>";
}
echo "<tr><td><b>total</b></td>";
";
You have to implement a total counter like :
// Print data
foreach($data as $_row_name => $_row_data) {
// Add the dash (-) for empty cells
$_row_data[$_row_name] = '-';
$total_row = 0; //initialize
echo "<tr><td width='10%'>{$_row_name}</td>";
foreach($columns as $_col_name) {
echo "<td>{$_row_data[$_col_name]}</td>";
if ($_row_data[$_col_name] != '-') {
$total_row += $_row_data[$_col_name];
$total_col[$_col_name] += $_row_data[$_col_name];
}
}
echo "<td>{$total_row}</td>";
echo "</tr>";
}
echo "<tr><td><b>total</b></td>";
foreach ($total_col as $name => $val) {
echo "<td>$val</td>";
}

Categories