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)
Related
I am trying to display information taken from a mysql database but i do not want to display the 'id' field in the results. i got the displaying part down just fine. just need to remove a field from the view.
$plantarray = array();
if($result = $mysqli->query($hoyaquery)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$plantarray[] = $row;
}
}
}
The code will return a nested array of results but it includes the tables id field.
its then displayed using:
<?php if (count($plantarray) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($plantarray))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($plantarray as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
ive tried to loop through the outside array and target the key 'id' but it doesnt do anything at all if i unset the id.
foreach($plantarray as $key){
unset($key['id']);
}
this does nothing at all.
i know the problem is in the looping, because if i set an array with the same data and i unset['id'] then it removes the id.
$p = [ "id" => 3, "Family" => "Apocynaceae", "Genus" => "Hoya", "Species" => "curt" ];
unset($p["id"]);
print_r($p);
i could have this completely wrong. I'm not sure. I'm unsure where its going wrong.
The reason that your loop doesn't work is because you aren't unsetting the values in the array itself, rather in the "copy" that is generated during the foreach loop. If you want to use this solution then the right code looks something like this:
foreach($plantarray as &$key){
unset($key['id']);
}
The & symbol will pass the row by reference which will make your manipulations be kept in the original array.
That said, this is not a performant way of doing this. Ostensibly, you have a query somewhere above this code that looks something like
$hoyaquery = "SELECT * FROM plant-table-name";
Instead, just don't get the id column from the database at all.
$hoyaquery = "SELECT Family, Genus, Species FROM plant-table-name"
That will prevent you from needing to loop through all your results in the first place.
I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!
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);
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>
}
Having trouble using foreach to output the contents of a mysql table. The table (tr, td) etc is being printed out for each entry in the mysql table, but there is nothing between the td and /td tags, where each $item should be echoed.
$sql = 'SELECT domain FROM domainsuggestions';
$domains = mysqli_query($link, $sql); // get domain suggestions from table
<table>
<tr>
<td>Domain Suggestions</td>
</tr>
<?php foreach ($domains as $item): ?>
<tr>
<td><?php echo htmlspecialchars($item, ENT_QUOTES, 'UTF-8'); ?></td>
</tr>
<?php endforeach; ?>
</table>
Your logic for working with MySQL is quite off. You need to perform the query first, grab the resource ID of the results, and then loop through the results.
$sql = 'SELECT domain FROM domainsuggestions';
$results= mysqli_query($link, $sql); // get domain suggestions from table
<table>
<tr>
<td>Domain Suggestions</td>
</tr>
<?php while ($item = mysqli_fetch_assoc($results)): ?>
<tr>
<td><?php echo htmlspecialchars($item['domain '], ENT_QUOTES, 'UTF-8'); ?></td>
</tr>
<?php endwhile; ?>
</table>
foreach expects an iterable element, i.e. something that has many entries that it can iterate through. That's typically an array, but can also be an object that implements the Iterable interface.
What you get when running mysqli_query is a resource. That's just a handle on a MySQL result set. The data is not yet in PHP, MySQL just gave you a handle saying "okay, I got the results for you ready, come get them whenever you need to". Calling mysqli_fetch_assoc gets one result row from MySQL. Calling it again gets the next, and the next and so on. This is not a process you can iterate through, you can just keep calling mysqli_fetch_assoc until there are no more results.
That's why foreach does not work.