Please forgive me as I am beginner in PHP.
I am trying to populate 2 two column table with inventory information. With my current code, I have the below image:
I would like to have two stores next to each other in this table. i.e Store Number 2 and Store Number 7 on the table row in the table, then Store 10 and 11 on the same row, and so on. Below is the code I am using so far to achieve this:
global $wpdb;
$result = $wpdb->get_results(
$wpdb->prepare( "
SELECT STORE_NAME,REPLACE(STORE_NAME, ' ', '-') as STOREURL, INVENTORY, STORE_NUMBER FROM StoreInventory
WHERE SKU = %s",
$product_sku
)
);
if ($result){
echo '<table class=\'inventory\'>';
foreach($result as $row) {
echo '<tr><td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td></tr>';
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}
The problem I am having is that I am looping through the record set row by row, and adding the data to each row. I have attempted to have a loop inside a loop, which will not give me the correct results.
Is it possible to split the result set into two multi-dimensional arrays and loop through each one separately then add them to the table? Can I call out a specific row with a counter within the loop?
Any advise or direction would be a great help.
A relatively simple approach would be to create a dummy variable to store the column. EX:
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td><div><a href=\'https://mystore.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>Store Number: ' . $row->STORE_NUMBER . '</a><br/>' .$row->INVENTORY. ' on hand. </div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</tr></table>';
Final answer based on ARubiksCube's answer:
if ($result){
$column_number = 0;
echo '<table class=\'inventory\'><tr>';
foreach($result as $row) {
echo '<td \' width=\'50%\' ><div><a href=\'https://shopliquornl.com/stores/'. $row->STOREURL . '\' target=\'_parent\'>' . $row->STORE_NAME . '</a><br/>' .$row->INVENTORY. ' on hand</div></td>';
$column_number += 1;
if ($column_number == 2) {
echo '</tr><tr>';
$column_number = 0;
}
}
echo '</table>';
} else {
echo '<table class=\'nostock\'><td>This item is out of stock, check back later for updated information!</td></table>';
}
Related
I want to display 9 different tables from my sql database in 9 different html created tables on the website.
In detail: I have 9 tables ("dt_bookmarks_01", "dt_bookmarks_02" etc.) with 4 columns "id" (which is primary and auto increment), icon (for favicon), link (url) and text (for the display text).
I've created 9 different html tables with bootstrap and want to output the content of each table in a different bootstrap table of my site.
My problem is that i have no idea how to get different "foreaches" or counter for each different table.
To automaticaly add new rows to the bootstrap table I use the count and foreach function. problem here is: I dont know how to seperate them from each other. If i have 4 entries in sql table 1 it multiplies the one and only entrie of sql table 2 to match the current count of 4.
I am very new to sql and php so I guess I just miss some fundamental functions or something.
document header:
php
$sql = "
SELECT *
FROM dt_bookmarks_01, dt_bookmarks_02";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
and for the html table I use:
php
<tbody>
<!--begin: SQL Selection -->
<?PHP
$count = 0;
foreach($rows as $item){
if (!empty($item['icon'])) {
$icon = '<img src="assets/media/bm-icons/'. $item['icon'] . '">';
}else{
$icon = '<img src="assets/media/bm-icons/default.png">';
}
$count++;
echo "<tr>";
/*echo "<td>" . $count . "</td>";*/
echo "<td> " . $icon . "</td>";
echo "<td> <a href=\"" . $item['link'] . "\"'>" . $item['text'] . "</a> </td>";
echo "<td></i> ";
echo "</i></td>";
echo "</tr>";
}
?>
<!--end: SQL Selection -->
</tbody>
I do not have a database on hand to give you an answer with complete code, but here is the idea:
<?php
for ($i = 1; $i <= 9; $i++)
{
$query = "SELECT index1,index2 FROM dt_bookmarks_0$i";
echo "<h1>This is the content of table $i</h1>";
# RUN THE QUERY HERE !!!
echo "<table>";
# EXTRACT THE RESULTS
foreach $rows as $item
{
echo "<tr><td>$item[index1]</td><td>$item[index2]</td></tr>"
}
echo "</table>";
echo "<br><br>";
}
?>
Loop on your tables.
In each table loop, you output the HTML code to display it's content.
Avoid SELECT *, specify your indexes (research "sql why avoid SELECT *")
So you loop twice. One time to go through the tables, the other to loop on the results.
so here is the new working code.
header:
<?PHP
require_once('/htdocs/_nt/mysql/data.php');
$sql = "
SELECT *
FROM dt_bookmarks";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
?>
and for the table output:
<?PHP
$count = 0;
foreach($rows as $item){
if ($item['category'] == talk) {
$count++;
echo "<tr>";
echo "<td> " . $icontalk . "</td>";
echo "<td> <a href=\"" . $item['url'] . "\"'>" . $item['text'] . "</a> </td>";
echo "</tr>";
}else{
echo "";
}
}
?>
I am learning PHP and I want to know how to do an inner loop or nested loop with records in PHP. I will appreciate if somebody explains me how to do this type of loop in PHP.
I have this table in MySQL
[]
I just want to create a report table in PHP that looks like this:
So far, I know how to do a current loop with the code below but how could I do in the same loop and inner loop to show dishes like table above. I know how to create the format (table, spaces, etc) I just need the PHP logic to do this in the best way.
<?php
do { ?>
Table in here
<?php } while ($selecc = mysqli_fetch_assoc($conmenu)); ?>
The clean/direct approach should be something like this:
SELECT Client, Option, GROUP_CONCAT(Dish SEPARATOR ', ')
FROM table_name
GROUP BY Client, Option
Then with your data already grouped and glued together, just print your strings in a single loop of the result set.
Using a do {} while () is of no benefit here.
Here's an untested snippet...
if ($conmenu) {
echo '<table>';
echo '<tr><td>Client</td><td>Option</td><td>Dishes</td></tr>';
while ($row = mysqli_fetch_assoc($conmenu)) {
echo '<tr><td>' , implode('</td><td>', $row) , '</td></tr>';
}
echo '</table>';
}
For the record:
The maximum permitted result length in bytes for the GROUP_CONCAT() function. The default is 1024.
https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_group_concat_max_len
Also, $conmenu is iterable, so you could use a foreach instead of a while loop.
foreach ($conmenu as $row) { ...
If you want to do it the hard way...
SELECT Client, Option, Dish
FROM table_name
ORDER BY Client, Option
Then... (untested)
if ($conmenu) {
echo '<table>';
echo '<tr><td>Client</td><td>Option</td><td>Dishes</td></tr>';
$group = null;
foreach ($conmenu as $row) {
if ($group !== $row['Client'] . '_' . $row['Option']) {
if ($group !== null) {
echo '</td></tr>';
}
echo '<tr><td>' , implode('</td><td>', $row);
} else {
echo ", " , $row['Dish'];
}
$group = $row['Client'] . '_' . $row['Option']; // update group
}
echo '</td></tr>'; // close final iteration
echo '</table>';
}
I'm running a query on three columns; one column contains text, the other two contain numbers. I do a calculation on these numbers to get a new number called $average. I then spit out the result to an html table. The rows in the table are sorted in the order they come out of the database. I'm trying to sort the table so that the data is displayed from highest $average to lowest (while still be correctly associated with the correct text value from the first column).
I've tried some asort and foreach stuff, but I've only succeeded in making a mess of errors.
Any ideas as how I go about this?
Thanks.
This is the current state of play:
/ db query
if (!$result = mysqli_query($link,"SELECT quiz_name,
quiz_attempts,
cumulative_score
FROM scoredata")) {
echo("There was a problem: " . mysqli_error($link));
exit();
}
...
// got results?
if(mysqli_num_rows($result) >= 1) {
$output = "";
$output .= "<table>\n";
$output .= "<tr><th>Quiz name</th> <th>Played</th> <th>Avg. score</th></tr>\n";
while($row = mysqli_fetch_array($result)) {
$output .= "<tr><td>".str_replace('_', ' ', $row['quiz_name']) . "</td>";
$output .= "<td>" . $row['quiz_attempts'] . "</td>";
// calculate average score
$average = $row['cumulative_score']/$row['quiz_attempts'];
$output .= "<td>" . round($average,2) . "</td></tr>";
}
$output .= "</table>\n";
echo $output;
}
...
You can do calculation and sorting in your query:
SELECT
quiz_name,
quiz_attempts,
cumulative_score,
(cumulative_score/quiz_attempts) as score_avg
FROM scoredata
ORDER BY score_avg DESC
You can
let the db do the sorting (as suggested by other posters)
sort the data yourself (as you are trying to do)
let the user sort the data via JavaScript functions. My favourite is
http://www.javascripttoolbox.com/lib/table/
Make this your query
SELECT quiz_name,
quiz_attempts,
cumulative_score,
cumulative_score / quiz_attempts as avg_score
FROM scoredata
ORDER BY avg_score
This question already has answers here:
create dropdown menu on each loop assign database value to option element
(2 answers)
Closed 9 years ago.
Im working on a page for a sports team where the coach can select his team. What im trying to do is:
1) Print different positions
2) Assign next to position name, players who are ONLY relevant to the
position. (i.e if the positions name is flanker only flankers should
be displayed in the drop-down menu)
My logic for the above problem is:
Assign position names to array called $position Loop over array
querying database, with position having a different value after each loop.
Selected players that match the position gets assigned to an
array called $playerName
Print the $position variable
Create dropdown menu for each position
assign value
from $playername array to the option element in the drop down
menu.
Now there should be different positions with dropdown menus,
next to them, containing player names relevant to position.
//create position array
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="slectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info` WHERE `position` = '$pposition'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) { //create arrays
$id[] = $row['player_id'];
$playerName[] = $row['name'];
$playerLastName[] = $row['surname'];
// print position and open select element
foreach ($position as $playerPosition) {
print $playerPosition;
echo '<select>';
foreach ($playerName as $name) { //assign playername to position element
echo '<option>' . $name;
'</option>';
echo '</select>';
echo '<br />';
} //close assign player nae to position loop
} //end print position and open select loop
} //end while loop
} //end opening for each loop
echo '</form>';
unfortunately for me either my logic is wrong or my code is incorrect. This is the ouput I get: (Note only the name Tendai is displayed in all dropdown meus no other names appear)
If been struggling with this one all morning if someone could point me in the right direction it would be greatly appreciated
(note to modirators the picure above does not contain real names and is only a fictional database)
You can do it like this. the logic is something different
function get_players_by_position($position)
{
$query = "SELECT
`player_id`,
`name`,
`surname`
FROM `player_info`
WHERE `position` = $position
ORDER BY name ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
return $data;
}
foreach($position as $pposition){
$data = get_players_by_position($pposition);
echo $pposition;
echo '<select>';
foreach($data as $row){
echo '<option '.$row['id'].'>' . $row['name'].'</option>';
}
echo '</select>';
echo '<br />';
unset($data);
}
In your original code, you could remove the two foreach loops in the while loop. Use $pposition in place of $playerPosition and your code should work as expected. Here's your code, with my suggested changes, in your procedural style:
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="selectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info`
WHERE `position` = '$pposition'") or die(mysql_error());
echo '<select name="'. $pposition . '">';
while ($row = mysql_fetch_array($result)) {
print $pposition;
echo '<option value="' . $row['player_id'] . '">'.
$row['name'] .' '. $row['surname'].
'</option>';
} //end while loop
echo '</select>';
echo '<br />';
} //end opening for each loop
echo '</form>';
The code belows gives me only 18 records
<?php
$result4 = mysql_query("select Distinct Country from trendsmtable where WHORegionAC='Europe - all countries' GROUP BY Country ");
echo "<table width=880 align=center>";
echo "<tr><td colspan=4 style='font-family:Arial;'><b>European Region</b></td></tr>";
$num_columns4 = 4;
$num_rows4 = mysql_num_rows($result4);
$i=0;
while($row4 = mysql_fetch_assoc($result4)){
$results[$i] = $row4['Country'];
$i++;
}
unset($i);
$k=0;
for ($i=0;$i<=($num_rows4/($num_columns4+1));$i++){
echo '<tr>';
for($j=1;$j<=$num_columns4;$j++){
echo "<td width=220 style='font-family:Arial; font-size:12px'>".$results[$k].'</td>';
$k++;
}
echo '</tr>';
$k++;
}
echo "</table>";
?>
while the select statement
select Distinct Country from trendsmtable where WHORegionAC='Europe -
all countries'
returns 22 rows while I execute it in mysql which is correct!
Please help me to found the error.
Well, you have an extra $k++ in there that you don't need:
$k++; // keep this one
}
echo '</tr>';
$k++; // remove this one
}
Edit
I've gone through your code and I've made some edits. Hopefully they'll clean your issue along the way:
// got rid of group by. With a select distinct, it isn't necessary
$result4 = mysql_query("select Distinct Country from trendsmtable where ".
"WHORegionAC='Europe - all countries'");
// a good practice is to always double-quote your HTML attributes.
echo "<table width=\"880\" align=\"center\">";
echo "<tr><td colspan=4 style=\"font-family:Arial;\">".
"<b>European Region</b></td></tr>";
$num_columns4 = 4; // where does 4 come from.
// $results was never initialized before.
$results = array();
while($row4 = mysql_fetch_assoc($result4)){
// This is generally thought of as "cleaner" than using an index.
// And since there cannot be more than, say, 220 rows, cleanliness
// should be a high-priority standard.
$results[] = $row4['Country'];
}
// mysql_num_rows rarely provides any major benefit at all.
$num_rows4 = count($results);
foreach( $results as $key => $val )
{
// This happens every time we fill all columns and need a new row.
if( !( $key % $num_columns4 ) )
{
// makes it so that after the first time this closes the prev
// row before starting a new one.
if( $key ) echo '</tr>';
echo '<tr>';
}
// insert nag about CSS
echo '<td width="220" style="font-family:Arial; font-size:12px">'.
$val.
'</td>';
}
echo '</tr></table>';
I think the PHP looks a little odd, it looks like you are looping from 0 to (22 / 5)
then in the inner loop 4 times.
The group by should not make any difference as you are doing a select distinct
Your SQL code in the PHP file contains a GROUP BY clause, which can reduce the number of rows returned, if you have a country more than once in the db.