Display columns with rows in php table - php

Hey guys I need your help, I have this table
and I want to shows like this FIDDLE, really I don't know how to do this because sometimes just exist two columns(prov_name ) and sometimes exist more that two rows please help me if you can !
Hope you understand me. Thanks so much !
In this way I can be able to select data from Joomla.
$db =& JFactory::getDBO();
$query = 'SELECT prov_name FROM provprices where CA_id = '.$CA_id;
$db->setQuery($query);
$result = $db->loadObjectList();
$prov_name = $result[0];
echo $prov_name->prov_name;

First off, in order for your data to be presented like that obviously it must be grouped accordingly.
The first row is, the prov_name's, so you can use GROUP BY or you cal also do it in PHP. Based of the sample data, it should have from 1 to 6.
Then the second row is just a simple unitval and totval according to how many prov_name's.
Third is the and the rest is the grouping of the values. See Example:
$db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME;charset=utf8', 'USERNAME', 'PASSWORD');
$data = array();
$results = $db->query("SELECT * from YOUR_TABLE_NAME");
while($row = $results->fetch(PDO::FETCH_ASSOC)) {
$data[$row['prov_name']][] = $row;
}
$keys = array_keys($data);
$size = count($keys);
$vals = array();
// grouping:
// if there are six (cam1 to cam6)
// then group them by cam1, ... to cam6, then repeat until theres no more left
while(count($data) > 0) {
foreach($keys as $key) {
if(!empty($data[$key])) {
$vals[] = array_shift($data[$key]);
} else {
unset($data[$key]); // remove them if empty
}
}
}
$vals = array_chunk($vals, $size); // split them by how many prov_names
?>
<table border="1" cellpadding="10">
<!-- PROV NAMES -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<th colspan="2"><?php echo "prov_name $x"; ?></th>
<?php endfor; ?></tr>
<!-- unitval totvals -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<td>unitval</td><td>totval</td>
<?php endfor; ?></tr>
<!-- the grouped values -->
<?php foreach($vals as $val): ?>
<tr>
<?php foreach($val as $v): ?>
<td><?php echo $v['unitval']; ?></td>
<td><?php echo $v['totval']; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

I think you must do this first,
try looping to show prov_name in horizontal,
and then you fetch again in query with
"SELECT * FROM table_test where prov_name = '$prov_name'"
in Variable $prov_name you must have a value with CAM2 or CAM3 .etc
sorry just a logic :)

Related

Two arrays in foreach loop.

I want to fill in the table. The database is filling the array, but this method didn't work. What is the problem? How to use foreach loop?
<?php
$a = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.ustsayfaid");
$a->execute(array());
$b = $a->fetchALL(PDO::FETCH_ASSOC);
$c = $a->rowCount();
$q = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.altsayfaid");
$q->execute(array());
$w = $q->fetchALL(PDO::FETCH_ASSOC);
$e = $q->rowCount();
if($c){
foreach($b as $w and $m as $n){
?>
<tbody>
<tr>
<td>
<?php echo $m["sayfa_adi"];?>
</td>
<td>
<?php echo ($n["sayfa_adi"]);?>
</td>
</tr>
<?php
}
}
?>
</tbody>
Here's what I came out with.
<?php
$firstQuery = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.ustsayfaid");
$firstQuery->execute(array());
$firstQueryResults = $firstQuery->fetchALL(PDO::FETCH_ASSOC);
$firstQueryCount = $firstQuery->rowCount();
$secondQuery = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.altsayfaid");
$secondQuery->execute(array());
$secondQueryResults = $secondQuery->fetchALL(PDO::FETCH_ASSOC);
$secondQueryCount = $secondQuery->rowCount();
if ($firstQueryCount > 0 && $secondQueryCount > 0) {
?>
<tbody>
<?php foreach ($firstQueryResults as $firstQueryKey => $firstQueryRow) { ?>
<tr>
<td>
<?php echo $firstQueryRow["sayfa_adi"];?>
</td>
<td>
<?php echo ($secondQueryResults[$firstQueryKey]["sayfa_adi"]);?>
</td>
</tr>
<?php
}
}
?>
</tbody>
I changed the names of the variables for readability, and I adapted the table for using the information you provided... there are still some flaws connected with indexes that might be different for each SELECT, but that is another problem.
I also interpreted some variables that were missing as the variables you had but, for some reason, wrote wrong.
you cannot be used and in a foreach i think you want to use 2 foreach here and your <tbody> should be out of the loop

SQLite and PHP displaying data from using array

I wanna display columns from specific table and I did it BUT im totally new to this, and I'm trying to build this site for myself and community I have so they can redeem gear from points they get by posting. Script works fine but I wanna get rid of this stuff Array аnd arrows, you can see it on screenshot I've provided, I want to display only username and points but not whole thing.
https://gyazo.com/1cbb85765ae3fd21efa76215b7042329
here is a code that I'm using:
<?php
$db = new SQLite3('phantombot.db');
$sql = "SELECT variable, value FROM phantombot_points";
$result = $db->query($sql);//->fetchArray(SQLITE3_ASSOC);
$row = array();
$i = 0;
while($res = $result->fetchArray(SQLITE3_ASSOC)){
if(!isset($res['variable'])) continue;
$row[$i]['variable'] = $res['variable'];
$row[$i]['value'] = $res['value'];
$i++;
}
print_r($row);
?>
You can create the table for that
<table>
<tr><th>Username</th><th>Points</th></tr>
<?php foreach($row as $datum): ?>
<tr>
<td><?php echo $datum['variable'];?></td>
<td><?php echo $datum['value'];?></td>
</tr>
<?php endforeach;?>
</table>

Updating dynamic links from database results

I'm playing around with PHP a bit and am trying out dynamic links. My problem is that the corresponding ID is not correctly to the URL with my code, so I have the same link everytime.
Here is what I have:
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
mysqli_select_db($connection, 'filme');
$query = "SELECT * FROM filme";
$result = mysqli_query($connection, $query);
$filmID = mysqli_fetch_assoc($result);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row['Name'] . " - " . $row['Preis'];
}
$chunks = array_chunk($array, 4);
$filmID = mysqli_fetch_assoc($result);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $val) {
?><td><?php echo $val; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysql_close();
?>
What I'm trying to do is display a table with four columns, that in every cell has a string in the format of "Film name - Price" and this string should be a link that leads to the page with the according ID. This code does display my four column table, but it is missing the first item of my database and the ID is the same for every link, namely the ID of that first film that is missing. So every URL looks like this:
http://localhost/dvd.php?Film_ID=1000
But the film with the ID 1000 is not even listed. I thought about putting that nested foreach loop in a while loop with
while($filmID = mysqli_fetch_assoc($result)){
...
}
But with that I get a blank page.
I have just about no experience with php, so sorry if I'm missing something really obvious.
You are going about this the wrong way. There's no link here between the contents of $array and $filmID. Indeed, $filmID is probably empty because you've already run through your result set earlier. Imagine your database result set is like a stack of papers. Each call to fetchAssoc() reads one sheet of paper, and sets it aside. Once you reach the end of the result set, there's nothing left to read, so your next calls will fail. You need to do all your database fetch in a single loop. As well, you should not be using mysql_close() with mysqli.
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
$connection->select_db('filme');
$query = "SELECT * FROM filme";
$result = $connection->query($query);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
$chunks = array_chunk($array, 4);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $film) {
?><td><?php echo "$film[Name] - $film[Preis]"; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysqli_close();
Or, better yet, just use the more modern PDO library:
<?php
$connection = new PDO("mysql:host=localhost;dbname=filme", "root", "password");
$query = "SELECT `Film_ID`, `Name`, `Preis` FROM filme";
$result = $connection->query($query);
$chunks = array_chunk($result->fetchAll(PDO::FETCH_ASSOC), 4);
?>
<table class='filme'>
<?php foreach ($chunks as $chunk):?>
<tr>
<?php foreach ($chunk as $film):?>
<td>
<?=htmlspecialchars("$film[Name] - $film[Preis]")?>
</td>
<?php endforeach?>
</tr>
<?php endforeach?>
</table>
Note this code is much more efficient and easier to read due to use of alternative syntax and short echo tags to keep PHP and HTML mixing to a minimum. Ideally your PHP would be in a totally separate file.

how to associate column record with table header?

I have a mysql table, one of its columns called parking space has a number in it. However, for some records the 'parking space'-column is empty. Now, I want to call just this column in a page table where the column heads are numbered from 1 - 200 (first column: 1; second column: 2;....) So, if there is the value '12' in the 'parking space'-column, then this shall show up in column '12' and so on, and if there is no entry for a number then the column in the page table shall be left empty. How can I associate the numbers in 'parking space' with that page table?
...
<?php
$pagetable=array('1','2','3','4','5','6');//...until 200
foreach($pagetable as $value){
?>
<table border="1px" cellspacing="1" cellpadding="1">
<tr>
<th>
<?php echo $value ?>
</th>
</tr>
<?php
}
include("dbinfo.inc.php");
include_once("config.php");
$result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results = mysql_num_rows($result);
if ($results > 0){
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"id");
$park=mysql_result($result,$i,"park");
?>
<tr>
<td style="background-color:;">
<?php echo $park; ?>
<br>
<?php if($park!=''){ ?>
<?php echo $id; ?>
<?php
}
?>
</td>
</tr>
<?php
$i++;
}
}
?>
...
There are two ways, you can do this.
Create all 200 rows on the database table and query it. This will omit almost all of the headache to get what you want.
Do a for loop from 1 to 200 and compare the active item if it exists on the mysql results. For this you require an continuous numeric entry in the database to identify each columns individually.
What I mean is? Column 1 in the should have corresponding record indicating 1 somewhere in its record.
Here is an example of this:
$result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results = mysql_num_rows($result);
if ($results > 0) {
$num=mysql_numrows($result);
$rows = array();
while($row = mysql_fetch_row($result)) {
$rows[$row['id']] = $row;
});
//Now process it
}
Try this:
<?php
include("dbinfo.inc.php");
include_once("config.php");
$spaces = range(1, 200);
$results = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results_count = mysql_num_rows($result);
if ($results_count > 0) {
for ($i = 0; $i < $results_count; $i++) {
$parks[] = mysql_result($results, $i, "park");
}
}
?>
<table>
<tr>
<?php foreach ($spaces as $space): ?>
<td><?php echo $space ?></td>
<?php end foreach ?>
</tr>
<tr>
<?php foreach ($parks as $park): ?>
<td><?php if ($park > 0) { echo "$space"; } else { echo " "; } ?></td>
<?php end foreach ?>
</tr>
</table>
Start with this and tell me what you get.
Ok, I got it changed a little. Now it ahows me all from 1-200 and it shows the parking spaces values, but these values are not associated with the numbers. it looks to me like it puts them according to the id, for example in my table the customer on parking space 165 has the id 4 and therefore it doesnt put 165 to 165 but 165 to 4
<?php
include("dbinfo.inc.php");
include_once("config.php");
$spaces = range(1, 200);
$results = mysql_query("SELECT * FROM contacts");
$results_count = mysql_num_rows($results);
if ($results_count > 0) {
for ($i = 0; $i < $results_count; $i++) {
$parks[] = mysql_result($results, $i, "park");
}
}
?>
<table>
<tr>
<?php foreach ($spaces as $space){ ?>
<td><?php echo $space; ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($parks as $park){ ?>
<td><?php if ($park!='') { echo $park.'<br>';} else { echo " "; } ?></td>
<?php }?>
</tr>
</table>

MYSQL ordering columns in my query

I have been working on trying to get a bunch of data to work in a table structure displayed neatly using PHP, and I must say I am having a difficult time. I have finally been able to call the columns so that in case I add a field it will always add it in my table, and I hope for this to be very easily managed. However, when I initially set up the table, I put it in a random order. Now when I come use the DESCRIBE table it gives them to me in exact order, and I cannot find a way to organize them better. It would not make sense to say have month/year at the end of the database for my form that I have.
<?php
require 'connect.php';
?>
<h3>Monthly Finances | Add New Month </h3>
<table border="1" bordercolor ="#000000">
<tr>
<?php
$columns = "DESCRIBE `month` ";
if($query_run_columns = mysql_query($columns)){
$columnNames = array();
while($column = mysql_fetch_assoc($query_run_columns)){
echo '<th>'.$column['Field'].'</th>';
}
}else{
echo'sql error';
}
?>
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
while($row = mysql_fetch_assoc($query_run)){
$rent = $row['rent'];
$electric = $row['electric'];
$cable = $row['cable'];
$cellphone = $row['cellphone'];
$renters = $row['renters'];
$month = $row['month'];
$year = $row['year'];
echo '<tr>';
echo '<td align="center">'.$month.'</td>';
echo '<td algin="center">'.$year.'</td>';
echo '<td align="center">'.$rent.'</td>';
echo '<td align="center">'.$electric.'</td>';
echo '<td align="center">'.$cable.'</td>';
echo '<td align="center">'.$cellphone.'</td>';
echo '<td align="center">'.$renters.'</td>';
echo '</tr>';
}
}else{
echo 'query error';
}
?>
<br>View by month
</table>
<form action="index.php" method="GET">
<select name="months" value="all">
<?php
$gathermonths = "SELECT `month`, `year` FROM `month";
if($query_month_selector = mysql_query($gathermonths)){
while($month_row = mysql_fetch_assoc($query_month_selector)){
$month = $month_row['month'];
$year = $month_row['year'];
echo '<option value="'.$month.' '.$year.'">' .$month.' '.$year.'</option>';
}
}
echo $_GET['months'];
?>
<input type="submit" value="View Selected Date"></input>
</select>
</form>
My code is very far from complete, or orderly but I have been slacking on this project and I will clean it up more when I have more time. But if you could please give me a hand on an efficient organizational method that would be appreciated.
Do your tables contain an index/id?
You can easily order them in ascending/descending by "ORDER BY"
ALTER TABLE `table_name` ORDER BY `id`
Note default ORDER BY is in ascending order. Put DESC at the end if you want descending.
If you want your mysql query to output results in a nice ordered fashion, you can also use ORDER BY in the query:
$gathermonths = "SELECT `month`, `year` FROM `month` ORDER BY `month` DESC";
There is also GROUP BY functions in case you wanted to group your results by month:
$gathermonths = "SELECT `month`, `year` FROM `month` GROUP BY `month`";
Instead of the DESCRIBE query, you could use mysql_fetch_field. Then columns will always be in the same order you have on your SELECT:
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
// Loop the columns to build the table headers
echo '<table>';
echo '<tr>';
while ($i < mysql_num_fields($query_run)) {
$field = mysql_fetch_field($query_run, $i);
echo '<th>' . $field->name . '</th>';
$i++;
}
echo '</tr>';
// Your current data loop
while($row = mysql_fetch_assoc($query_run)){
// (...)
}
echo '</table>'
}
?>
Since you're already specifying which columns you're fetching, simply output the column headers explicitly rather than querying the database.
Contrariwise, if you want to abstract the HTML table generation code so that it works with arbitrary SQL tables (thus separating data access from display), record the column names as you generate the column headers in an array, then iterate over this array when outputting rows. You can also do away with the $rent = $row['rent']; assignments, as they gain you nothing. Using PDO:
/* data access */
$finances = $db->query('SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month`');
$columns = array();
for ($i = 0; $i < $finances->columnCount(); ++$i) {
$meta = $finances->getColumnMeta($i);
$columns[$meta['name']] = ucwords($meta['name']);
}
/* data display. Note this is completely independent of the type used to store
the colum & row data. All that matters are that $columns and $finances are
Traversable
*/
?>
<table>
<thead>
<tr>
<?php foreach ($columns as $name => $label): ?>
<th><?php echo $label ?></th>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach ($finances as $monthly): ?>
<tr>
<?php foreach ($columns as $name => $label): ?>
<td><?php echo $monthly[$name]; ?></td>
<?php endforeach ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Error handling and abstraction into modules left as an exercise.

Categories