Creating a table with PHP foreach function - php

I'm in a class called database programming. We got a data set and and put it into our servers. Now I have to use a jquery plugin to help visualize that data. I am using Graph Us plugin and trying to use the "Fill In" option.
My professor helped me create this function:
<?php
include 'connect.php';
$country_query = "SELECT DISTINCT Country FROM FemaleMaleRatioNew";
$result = mysqli_query($sql_link, $country_query);
$new_row = array();
while ($row = mysqli_fetch_assoc($result)) {
$country = $row['Country'];
$query = sprintf("SELECT Year, Value FROM FemaleMaleRatioNew WHERE Country = '%s'", $country);
$country_result = mysqli_query($sql_link, $query);
while ($country_row = mysqli_fetch_assoc($country_result) ) {
$new_row[$country][] = array('year' => $country_row['Year'],
'value'=> $country_row['Value']
);
}
}
//print_r($new_row);
?>
the print_r($new_row); is only there to make sure it works and it does, it prints out the array when activated.
He then guided me to create the table like this:
<body>
<table id="demo">
<?php foreach($new_row as $row):?>
<tr>
<td><?=$row['year'];?></td>
<td><?=$row['country'];?></td>
</tr>
<?php endforeach;?>
</table>
<script type="text/javascript">
$(document).ready(function() {
// Here we're "graphing up" only the cells with the "data" class
$('#demo td').graphup({
// Define any options here
colorMap: 'heatmap',
painter: 'fill',
// ...
});
});
</script>
</body>
What else do I need to do to get the table to work? I can't seem to figure it out. All it does is come out blank.
I'm sorry if this question isn't worded correctly or if I have not been clear on anything please let me know.

You have multiple rows for each country in your $new_row variable. You have to iterate over countries first and then over the individual rows of data:
<?php foreach($new_row as $country => $rows): ?>
<?php foreach($rows as $row): ?>
<tr>
<td><?=$country;?></td>
<td><?=$row['Year'];?></td>
<td><?=$row['Value'];?></td>
</tr>
<?php endforeach;?>
<?php endforeach;?>
Also please note that you need colon ':' not semicolon ';' after the foreach statement. This syntax (which is less known) is described here: http://php.net/manual/en/control-structures.alternative-syntax.php
If you want to display some sort of aggregate (for example sum) per country and you want to calculate it in PHP (as opposed to MySQL) you can do it like this:
<?php foreach($new_row as $country => $rows):
$sum = 0;
foreach($rows as $row):
$sum += $row['Value'];
endforeach;
?>
<tr>
<td><?=$country;?></td>
<td><?=$sum;?></td>
</tr>
<?php endforeach;?>

You should be using a single JOINed query to do this stuff, but you may not have gotten that in class yet. Since it's homework, I won't give you the flat-out answer, but here's the pseudo-code:
$countries = SELECT DISTINCT Country FROM YourTable;
while($country_row = fetch_row($countries)) {
echo $country_row['Country'];
echo <table>;
$status = SELECT Year, Value FROM YourTable WHERE Country=$country_row['Country'];
while($stats_row = fetch_row($status) {
echo <tr><td>$stats_row['Year']</td><td>$stats_row['Value']}</td>
}
echo </table>
}

Related

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>

Split query in several positions

I have a website where I need to split a result query that gives me all my groups because I want to handle all the groups individualy.
This is my code ( result 6 is the query i make to obtain all the group names). But the problem is that all the result appear in the same position -> [0] zero.
This is an image of the problem
<?php while ($row = mysqli_fetch_array($result6)){ ?>
<tr>
<?php if(strlen($row['groupname'])>0){ ?>
<?php $groups = $row['groupname'];
$dividedGroups= (explode(",",$groups));
print_r($dividedGroups)
?>
</br>
<?php } ?>
</tr>
<?php } ?>
I guess more data is needed, but as far as I can tell you are ending with an array of arrays.
After this line:
$dividedGroups= (explode(",",$groups));
Try to add this two lines in order to transform it to a simple array:
$dividedGroups= array_map("array_shift",$dividedGroups);
$dividedGroups= array_map("array_values",$dividedGroups);
You don't need to split by comma as each row represent a group:
<?php
while ($row = mysqli_fetch_array($result6)) {
if(strlen($row['groupname'])>0) {
?>
<tr>
<td>
<?php echo $row['groupname']; ?>
</td>
</tr>
<?php
}
}
?>
Or, if the row is not a group you can group it by groupname before displaying:
$results = [];
while ($row = mysqli_fetch_array($result6)) {
$results[$row['groupname']] = isset($results[$row['groupname']])
? array_merge($results[$row['groupname']], [$row])
: [$row];
}
print_r($results);

Loop through database record to generate table

I want to construct an html table based on the returned results from the database. Assuming I have a table called constraints in my database and a column called riskName and it has these values: Security, Financial, Legal and Technical as shown in the image below. How do i loop through my database and come up with this table. I have tried different approach but no has worked. Here is my code so far:
<?php
error_reporting(0);
$optioner = 12;
$getObs = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
$result = $riski->fetch(PDO::FETCH_ASSOC);
while($getObs->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>".($result['riskName'])."<td><tr>";
//...other code
}
?>
</tbody>
<?php };
?>
I'm not sure if this will give you the exact table you're looking for, but it should at least put you on the right lines. Also, you weren't keeping your variables the same and notice how $result is set in the while loop
$optioner = 12;
$riski = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
?>
<form>
<table>
<tr> <th>i</th> <th>Importance</th> <th>How Much More?</th> <tr>
<?php
while($result = $riski->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
echo '<td>'. $result['riskName']).'<td>';
echo '<td>';
for ($i=1;$i<10;$i++){
//radio buttons go here
}
echo'<tr>';
//...other code
}
?>
Sorry I couldn't help more.
Hope this works for you.

How do I set column names in dynamic tables?

I am retrieving a result from the database where the column names are script_id, script_name etc, now what I am doing is after fetching the results from the table say I fetched 2 columns, example script_id and script_name so am saving the names separated with a comma and using a loop, but what if I am not aware how many parameters the user has selected, and how many will it return? for example what am doing
<table>
<tr>
<?php
$columns = explode(',', $fetch_column_list);
foreach($columns as $throw_names) {
echo '<td>'.$throw_names.'</td>';
}
?>
</tr>
//And here I loop the results
</table>
But what If am having a form with different parameters to select
So here I cannot have a pre-defined list of my defined column names as user may or may not have seleted the column
So how I can generate the table dynamically with MY DEFINED COLUMN HEADERS on the front-end
You don't need to know how many columns you've got.
Instead of numbers you have to use field names
<?
$trans = array (
'script_name' => 'Fancy script name field header',
'script_value' => 'Fancy script value field header',
}
$data = $db->getAll("SELECT * FROM table");
$keys = array_keys($data[0]);
?>
<table>
<tr>
<? foreach ($keys as $k): ?>
<td><?=$trans[$k]?></td>
<? endforeach ?>
</tr>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $one): ?>
<td><?=$one?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
How do you fetch your data?
If you use a function like mysqli_fetch_assoc, you may use
$row = mysqli_fetch_assoc( ... );
$columns = array_keys($row)

msql fetch array no longer listing all results

I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.

Categories