Loop through database record to generate table - php

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.

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>

php/mqsql multiple calls to DB and multiple loops - different logic needed

Firstly let me apologise for my vague question title, this is my first post on this site; after spending 2 days searching for the answer to my question (and getting quite close in some cases) I've hit a wall. Normally I can find everything I need from stackoverflow but this time I've run out of ways to word my question in the search bar.
I have a mysql table containing data for clothes (tbl_clothing) and in this table (I've simplified this for my problem) I have columns: style, colour_url, size, carton_price
The 'style' is for a particulate type of garment $row['style'] in the first sql statement comes from the initial request to the database to find out if the users choice is actually a valid choice (don't worry I've sanitized it, no direct user input is ever used!)
I am grouping by colour_url to create an array of all the colour variations for the chosen style. Incidentally the colour_url is also the actual url to the image file for that colour (used later). Yes this does mean that in the database there is repeating data, the colour_url is repeated as many times as there are sizes for that colour - I've inherited it and can't change that yet.
I then iterate over this array 'foreach' of the different colours and perform another DB lookup to select all sizes and prices for the chosen style and the current colour.
Still in the above foreach loop I perform a while loop to create a second array to hold the sizes and prices (multiple rows are returned from the DB).
Still in the above foreach loop I perform another foreach loop on the second array to create the table structure for outputting.
This is now screaming at me that it is not the best way of achieving what I'm tying to do.
Am I just over thinking this or is there a much simpler way of doing things? I've tried doing a single sql lookup to retrieve a multidimensional array all in one hit but then cant separate out the data into correct groups I've been over and over transposing arrays re-looping through the array creating other "reference" arrays all without any success.
The basic logic works like this:
1 style = many colours
1 colour = many sizes
1 size = 1 price
And i'm trying to get a table output (for each colour) like this:
_________________________________
| (IMG A) | Size(1) | Size(2) | Size(3) |
| colour_A | Price(1) | Price(2) | Price(3) |
|_________|_______________________|
_________________________________
| (IMG B) | Size(1) | Size(2) | Size(3) |
| colour_B | Price(1) | Price(2) | Price(3) |
|_________|_______________________|
Here is my code, it does the job but this cant be the best way to do it:
$sql = "SELECT colour_url FROM tbl_clothing WHERE style = '".$row['style']."' GROUP BY colour_url";
$result = $mysqli->query($sql);
$numRows = $result->num_rows;
if ($numRows != 0){
while ($rowS = $result->fetch_assoc()){
$aResults[] = $rowS['colour_url'];
}
$result->free();
foreach ($aResults as $k=>$v){
echo "<table><tr><td rowspan='2'><img title='' alt='' src='".$v."' /></td>";
$sql = "SELECT size, carton_price FROM tbl_clothing WHERE style = '".$row['style']."' AND colour_url = '".$v."'";
$result = $mysqli->query($sql);
$numRows = $result->num_rows;
if ($numRows != 0){
$aSizePrice = array();
while ($rowS = $result->fetch_assoc()){
$aSizePrice[$rowS['size']] = $rowS['carton_price'];
}
$sizes = "";
$prices = "";
foreach ($aSizePrice as $key=>$val){
$sizes .= "<td>".$key."</td>";
$prices .= "<td>".$val."</td>";
}
}
$result->free();
echo $sizes;
echo "<tr>".$prices."</tr>";
echo "</tr></table>";
}
}
?>
Any help would be a hugely appreciated, even just a point in the right direction, a different opinion or even a sarcastic comment will do at this point...
One thing i might recommend right off the bat, seperate your concerns. You are trying to get data right from the database into your view layer. Instead, get your data, compile it into memory, THEN, display it. It will make your problem easier to solve right off the start.
For example:
//Prepare the data receptacle
$data = array();
//Query to data to work with
$result = $mysqli->query("SELECT * FROM tbl_clothing WHERE style = '".$row['style']."'");
$numRows = $result->num_rows;
while ($rowS = $result->fetch_assoc()){
//Make sure our data can be stored correctly into our structure
if(!isset($data[$row['style']])){ $data[$row['style']] = array(); }
if(!isset($data[$row['style']][$rowS['colour_url'])){ $data[$row['style']][$rowS['colour_url'] = array(); }
if(!isset($data[$row['style']][$rowS['colour_url']['sizes'])){ $data[$row['style']][$rowS['colour_url']['sizes'] = array(); }
if(!isset($data[$row['style']][$rowS['colour_url']['prices'])){ $data[$row['style']][$rowS['colour_url']['prices'] = array(); }
//Store the price and size
$data[$row['style']][$rowS['colour_url']['sizes'][] = $rowS['size'];
$data[$row['style']][$rowS['colour_url']['prices'][] = $rowS['carton_price'];
}
//At this point we have our data, let's just show it
?>
<table>
<?php foreach($data as $style => $color_urls){ ?>
<?php foreach($color_urls as $color_url => $content){ ?>
<tr>
<td rowspan="2">
<img title="" alt="" src="<?php echo $colour_url; ?>" />
</td>
</tr>
<tr>
<?php foreach($content['sizes'] as $size){ ?>
<td><?php echo $size; ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach($content['prices'] as $price){ ?>
<td><?php echo $prices; ?></td>
<?php } ?>
</tr>
<?php } ?>
<?php } ?>
</table>
This is just a quick draft, i might not have understood your question correctly, you'll have to fix the errors and the miscomprehensions yourself. At least you have a good start with this!
Well, let's start with your query. In your first query, you claim you're trying to get all of the colors for a given style. You can use the DISTINCT keyword for that
SELECT DISTINCT colour_url
FROM tbl_clothing
WHERE style = ?
But that's not what you're actually looking to get - you actually want all of the color/size combinations in your database for a given style, which you would likely want to select thusly:
SELECT colour_url, size, carton_price
FROM tbl_clothing
WHERE style = ?
Once you've done that, you want to parse it into a data structure. (you should be parameterizing your queries - I recommend the PDO library, so I'll show you how that would work).
<?php
$db = new PDO('connection', 'user', 'pass');
$query = $db->prepare('SELECT colour_url, size, carton_price
FROM tbl_clothing
WHERE style = :style');
$query->bindValue(':style', $row['style'], PDO::PARAM_STR);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$clothes = array();
foreach($results as $result){
if(!isset($clothes[$result['colour_url']]))
$clothes[$result['colour_url']] = array();
$clothes[$result['colour_url']][$result['size']] = $result['carton_price'];
}
?>
Your results are now in a series of nested maps - from $clothes[$color], you get a map from size to price. $clothes[$color][$size] will net you the price of a specific color and size, and you can choose to print them that way:
<?php
foreach($clothes as $color => $prices) {
$sizeStr = '<td>' . implode('</td><td>', array_keys($prices)) . '</td>';
$priceStr = '<td>' . implode('</td><td>', $prices) . '</td>';
?><table>
<tr>
<td rowspan="2">
<img title="" alt="" src="<?=$color?>" />
</td>
<?= $sizeStr ?>
</tr>
<tr>
<?= $priceStr ?>
</tr>
</table><?php
}
?>
Your code now reads a lot closer to english, which will make it easier to debug, and easier to pas on to others.

Retrieving mysql table data that is stored within a php variable array

My connection to my database was successful. I now have all of the data from a table stored as an array in a php variable named $data. I am trying to extract three rows from this variable and display them with html.
Here is what my code looks like (with the exception of the connection info being removed):
<?php
$data = mysql_query("SELECT * FROM specs")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
$rows[] = $row;
?>
I know that I can pull individual data from this variable and insert it into html successfully by entering code like this (for example):
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Model: <?php echo $row['name'];?></td>
</tr>
</table>
But my problem is that I want to display three separate rows of data from the database as three individual columns in a html table. (Hope that makes sense)
I've looked into how to do this with foreach and while but am not quite sure where I'm going wrong.
I'm hoping someone might be able to shed some light on this as I have read about foreach loops, while, and am still stuck! I'm also hearing that mysql_query is deprecated but ruled out not using this since our webserver is still using an old version of php and mysql and is not planning to update anytime soon.
Sorry if I'm not all here in my post - it's late and I'm tired. Thanks for your help in advance! I'll keep an eye on this in case anyone has questions.
This will print the array in a table with each row being 3 elements of the array.
echo "<table>";
for ($i = 0; $i < count($rows); $i += 3) {
echo "<tr>";
for ($j = 0; $j < 3; $j++) {
if (isset($rows[$i+$j]) {
echo "<td>Model: {$rows[$i+$j]['name']}</td>";
}
}
echo "</tr>";
}
echo "</table>";
It's simpler to limit the SQL to three rows, and then echo all incoming rows directly, without first adding to an array. That would waste resources.
<?php
echo "<table>";
$data = mysql_query("SELECT * FROM specs LIMIT 3")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data))
echo '<tr></td>', $row['name'], '</td></tr>';
echo "</table>";
?>
Ah, but now I see it's a year old question. I hope you learned a lot in the meantime.

Creating a table with PHP foreach function

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>
}

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