Unexpected asynchronous like behavior - php

I came across an unexpected behavior while creating drop downs.
DropDown.php
function getValue($content, $options){
if($options["valueByName"])
return $content;
else
return $content["value"];
}
function getName($content, $options){
if($options["valueByName"])
return $content;
else
return $content["name"];
}
function isSelected($content, $options){
if(isset($options["selected"])){
if(getValue($content, $options) == $options["selected"])
return " selected ";
else
return "";
}
else
if(getValue($content, $options)=="")
return " selected ";
else
return "";
}
function renderOption($content, $options){
echo (
"<option value=\"".getValue($content, $options)."\""
.isSelected($content, $options).">"
.getName($content, $options).
"</option>");
}
$asdf123 = 0; #<-------------------------------------IMPORTANT
function DropDownMenu($contents, $options)
{
$id = $options["id"];
$name = $options["name"];
$style = $options["style"];
$flag = $options["flag"];
$firstIsDefault = $options["firstIsDefault"];
global $asdf123; #<-------------------------------------IMPORTANT
echo($asdf123++);
echo ("<select id=\"{$id}\"
name=\"{$name}\"
class=\"btn
btn-outline-secondary
waves-effect
waves-light
keyword_selector\"
style=\"width:140px;
height: 22px;
float:left;height:35px;
padding: 4px 14px;
{$style}\"
{$flag}>");
if($firstIsDefault){
echo (
"<option value ".isSelected($contents[0], $options).">"
.getName($contents[0], $options).
"</option>");
for($i = 1; $i < count($contents); $i++)
renderOption($contents[$i], $options);
}else{
foreach ($contents as $i => $content)
renderOption($content, $options);
}
echo ("</select>");
}
Using Drop Down(in another php file)
require_once("DropDown.php");
DropDownMenu($customers, [
"id"=>"customer-dropdown",
"name"=>"customer_id",
"firstIsDefault"=> true
]);
DropDownMenu($classes, [
"id"=>"class-dropdown",
"name"=>"class",
"firstIsDefault"=> true,
"style"=>"margin-left:5px;"
]);
# Total 7 times called
Results In
| DropDown | DropDown | 01 DropDown | 0 DropDown | 2345 DropDown | DropDown | DropDown |
Behavior
When I checked the elements in browser, all of the option element were <option value="" selected="">text was different</option>. Where expected behavior is only the first option being selected.
I added variable asdf123 in DropDown.php to look what was happening. And as noted above Results in, is printed in the sequence of 0 1 0 2 3 4 5.
Why would this happen? Are PHP functions asynchronous? What is happening? What could be the cause?
EDIT: I have fixed all of the options were selected part. It was because I was using the key in the $contents were wrong. Instead of "value" I used "id". But I still don't know why the execution sequence was messed up.

$customers=[[value=>a,name=>aa], [value=>b,name=>bb], [value=>c,name=>cc]]; // needed to tests
$classes=[[value=>A,name=>AA], [value=>B,name=>BB], [value=>C,name=>CC]]; // needed to tests
$asdf123 = 0;
function getValue($content, $options){ return ($options[valueByName]) ? $content : $content[value];}
function getName($content, $options){ return ($options[valueByName]) ? $content : $content[name];}
function isSelected($content, $options){ return (getValue($content, $options) == $options[selected]) ? ' selected' : '';}
function renderOption($content, $options){ echo '<option value="'.getValue($content, $options)."\"".isSelected($content, $options).">".getName($content, $options)."</option>\r\n"; }
function DropDownMenu($contents, $options){
echo $GLOBALS[asdf123]++."\r\n";
foreach([id, name, style, flag, firstIsDefault] as $val){ $$val = $options[$val];}
echo "<select id=\"$id\" name=\"$name\" \r\n class=\"btn btn-outline-secondary waves-effect waves-light keyword_selector\"\r\n style=\"width: 140px; height: 22px; float: left; height: 35px; padding: 4px 14px; \r\n $style\" \r\n $flag>\r\n";
if($firstIsDefault){
echo '<option value=""'.isSelected($contents[0], $options).'>'.getName($contents[0], $options)."</option>\r\n"; // lost ' ="value" ' , ' " ' , html syntax!!!!
$j = count($contents); // don't count every time
for($i = 1; $i <= $j; $i++){ renderOption($contents[$i], $options);} } // $i < $j is incomplete
else{ foreach ($contents as $key => $content) renderOption($content, $options);}
echo "</select>\r\n";}
DropDownMenu($customers, [id=>'customer-dropdown', name=>customer_id, firstIsDefault=> 1]);
DropDownMenu($classes, [id=>'class-dropdown', name=>'class', firstIsDefault=> true, style=>'margin-left:5px;']);
Just clean up, fix html and css syntax, fill empty values and will work fine.
Selected is only last option - as you set it.
... that's not pretty code, you know?
For html, css use Validator, please

Related

Change background color of a cell when next value is different from the preceding one

I've been around for years on Stack but this is my first time posting. I'm working on a website (php + mysql) and the following problem is driving me absolutely nuts.
I have a table with 2 columns: Size and Amount. The table is generated by a basic php script simply outputting values stored in the database as rows in the table. Super basic, no fancy stuff there:
SELECT Size, Amount FROM database WHERE product = 'product123' ORDER BY Size ASC
The php echo outputs an html table displaying Size and the corresponding available packs (Amount).
Echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>'
Some Sizes are available in different Amounts, so therefore a particular Size can appear multiple times. Example:
Size | Amount
1 | 10
1 | 50
2 | 10
2+ | 10
3 | 40
3+ | 25
3+ | 40
4+ | 25
What I'm looking to achieve is that rows containing the same Size have the same background color. So it should alternate, grouped by Size, and this is irregular unfortunately. Example:
Size | Amount
1 | 10 < yellow
1 | 50 < yellow
2 | 10 < transparent
2+ | 10 < yellow
3 | 40 < transparent
3+ | 25 < yellow
3+ | 40 < yellow
4+ | 25 < transparent
So if the next Size is different from the preceding one, the row background color should change. This way a single Size is alternately highlighted as a group. Note that Size 2 and 2+ (same for 3 and 3+) are considered to be different sizes, hence the background color should change.
I can't figure out how to achieve this with php. The difficulty is that I can't use an evaluation based on odd/even since there sometimes is a "+" involved, making not all Sizes numeric values. Changing the naming scheme to get rid of that "+" is not an option unfortunately.
I was thinking of somehow having php check, while generating the table row by row, if the next outputted Size is identical to the preceding one. If yes: no change in bg-color. If no: change bg-color. However I can't figure out what the best way is to code something like this. Any pointers in the right direction are much appreciated.
Just a MCVE:
// your data
$records[] = array('size' => "1");
$records[] = array('size' => "1");
$records[] = array('size' => "2");
$records[] = array('size' => "2+");
$records[] = array('size' => "3");
$records[] = array('size' => "3+");
$records[] = array('size' => "3+");
$records[] = array('size' => "4");
$lastSize = $records[0]['size'];
$color = "yellow";
foreach ($records as $record) {
if ($lastSize != $record['size']) {
$lastSize = $record['size'];
if ($color == "yellow") $color = "transparent";
else $color = "yellow";
}
$lastSize == $record['size'];
echo $record['size'].' - '.$color.'<br>';
}
// OUTPUT:
// 1 - yellow
// 1 - yellow
// 2 - transparent
// 2+ - yellow
// 3 - transparent
// 3+ - yellow
// 3+ - yellow
// 4 - transparent
Ok, we'll start at the end. You probably want to put your color on the <tr>. The cleanest way to do it would be using css classes.
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
We'll figure out how to get the right value into $newSize in a moment. Next, we need the css for classes above, so make sure this is in your styles somewhere:
.transparentRow {
background-color: transparent;
}
.yellowRow {
background-color: yellow;
}
Ok, lets rip the + off the size:
$plainSize = trim($record['size'], '+')
Ok, we use that for comparison, using an ever changing $oldSize valiable. Here is a full, functional, block:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
$newSize = false;
} else {
$newSize = true;
}
$oldSize = $plainSize;
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
Some cleanup can lead to this:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
$oldSize = $plainSize;
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
I hope that helped not just with this problem, but with an example of how you can approach many other problems. Start at the end, work your way back.
As my comment suggested, use a double foreach() + implode() (and yet another solution):
<?php
$array[] = array("size"=>1,"amount"=>50);
$array[] = array("size"=>2,"amount"=>10);
$array[] = array("size"=>"2+","amount"=>10);
$array[] = array("size"=>3,"amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>"3+","amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>'4+',"amount"=>30);
// Sort by size
foreach($array as $row) {
$new[$row['size']][] = $row['amount'];
}
?>
<table>
<?php
$i = 0;
// Loop through the sorted groups
foreach($new as $size => $amts) {
// Determine odd or even
$color = ($i % 2 == 0)? "yellow":"transparent";
?> <tr>
<td class="<?php echo $color; ?>"><?php echo $size; ?></td>
<td class="<?php echo $color; ?>"><?php echo implode("</td>".PHP_EOL."</tr>".PHP_EOL."<tr>".PHP_EOL.'<td class="'.$color.'">'.$size.'</td><td class="'.$color.'">',$amts); ?></td>
</tr>
<?php $i++;
}
?>
</table>
You can do this using php sessions like this
session_start();
$_SESSION["pre_val"]='not set';
$_SESSION["pre_class"]='transparent';
//in your loop for showing table
//your loop starts
if($_SESSION["pre_val"]==$record['size']){
$suitable_class=$_SESSION["pre_class"];
}
else{
if($_SESSION["pre_class"]=='yellow'){$suitable_class='transparent';}
else{$suitable_class='yellow';}
}
//setting current values to session
$_SESSION["pre_class"] = $suitable_class;
$_SESSION["pre_val"] = $record['size'];
Echo '<tr class="$suitable_class"><td>'.$record['size'].'</td><td>'.$record['amount'].'</td></tr>';
//your loop ends
in your css
.yellow{background-color:yellow;}
.transparent{ background-color: rgba(255, 0, 0, 0.5);}
hope this solve your problem
Some for loop fun while printing out the table
$rows = array(
array("size"=>"1" ,"amount"=>"10"),
array("size"=>"1" ,"amount"=>"50"),
array("size"=>"2" ,"amount"=>"10"),
array("size"=>"2+","amount"=>"10"),
array("size"=>"3" ,"amount"=>"40"),
array("size"=>"3+","amount"=>"25"),
array("size"=>"3+","amount"=>"40"),
array("size"=>"4+","amount"=>"25")
);
echo "
<table>
<thead>
<tr><th>Size</th><th>Amount</th></tr>
</thead>
<tbody>";
$bgColors = ['transparent','yellow'];
$bgColor = 0;
echo "
<tr>
<td class='" . $bgColors[$bgColor] . "'>" . $rows[0]["size"] . "</td><td>" . $rows[0]["amount"] . "</td>
</tr>";
for($i = 1, $max = count($rows), $lastSize = $rows[0]; $i < $max; $lastSize = $rows[$i], $i++) {
if($rows[$i]["size"] !== $lastSize["size"])
$bgColor = ($bgColor + 1) % 2;
echo "
<tr>
<td style='background-color:" . $bgColors[$bgColor] . "'>" . $rows[$i]["size"] . "</td><td>" . $rows[$i]["amount"] . "</td>
</tr>";
}
echo "
</tbody>
</table>";
And an unasked for JS solution (assuming you've printed out the table as usual)
var rows = document.querySelectorAll('#sizeTable tbody td[name=size]');
var bgColors = ['transparent','yellow'];
var bgColor = 0;
for(var i = 1, lastSize = rows[0], max = rows.length; i < max; lastSize = rows[i],i++) {
if(rows[i].innerHTML !== lastSize.innerHTML) {
bgColor = (bgColor + 1) % 2;
}
rows[i].style['background-color'] = bgColors[bgColor];
}
you can keep the current size on a variable and if it changes you can change the color.
<html>
<head><title> Sample - Menukz </title></head>
<body>
<?php
/* Sample data array with size and amount */
$product['product123'] = array
(
array("size"=>"1", "amount"=>10),
array("size"=>"1", "amount"=>50),
array("size"=>"2", "amount"=>10),
array("size"=>"2+", "amount"=>10),
array("size"=>"3", "amount"=>40),
array("size"=>"3+", "amount"=>25),
array("size"=>"3+", "amount"=>40),
array("size"=>"4+", "amount"=>25)
);
$pre_size=0;
$pre_init=1;
echo "<table>";
foreach($product['product123'] as $row)
{
echo "<tr>";
/* Initialize */
if(strcmp($pre_size, $row['size']) !== 0 && $pre_init ===1)
{
$pre_size = $row['size'];
$pre_init = 0;
}
/* Change track */
if (strcmp($pre_size, $row['size']) !== 0 && $pre_init ===0)
{
echo "<td>Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
$pre_size = $row['size'];
}
else
{
echo "<td>Not Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
}
echo "</tr>";
}
?>
</body>
</html>
Thanks all for the proposed solutions. Berriel's MCVE works like a charm! However Stack doesn't let me +1 the answer yet.
I have one additional question:
I also have a second table in which the output of the first column can be any article code consisting of 10 chars limited to [a-z][0-9]. Since there is no predefined scheme such as in the Size table, I can't hardcode/predict any output like in most of the proposed solutions. However I still want to color the rows it in the same way described in my opening post.
I am not familiar with Stored Procedures or PDO in mysql. Is there any way to work around arrays with predefined content and still achieve the color grouping of rows with the same article code?
You can accomplish this using a nested repeat region.
First select your product by group WHERE product = 'product123' GROUP BY size
<?php
require ('conn.php');
try {
$prod = 'product123';
$sql = "SELECT * FROM sizes WHERE product=:prod GROUP BY size";
$query = $conn->prepare($sql);
$query->bindValue(':prod', $prod, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die('failed!');
}
?>
Then get all the products in each group ordered by amount inside a nested repeat region.
Each "grouped row" will alternate colors.
<table width="200" border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Size</td>
<td>Amount</td>
</tr>
<?php
$i = 0;
do {
$i = $i + 1;
if ($i % 2 == 0){
echo '<tr bgcolor=#E4E4E4><td colspan="2">';
} else {
echo '<tr bgcolor=#EEEEEE><td colspan="2">';
}
try {
$group = $row['size'];
$sql = "SELECT * FROM sizes WHERE size=:group ORDER BY amount ASC";
$nested = $conn->prepare($sql);
$nested->bindValue(':group', $group, PDO::PARAM_INT);
$nested->execute();
$row_nested = $nested->fetch(PDO::FETCH_ASSOC);
$totalRows_nested = $nested->rowCount();
} catch (PDOException $e) {
die('nested failed');
}
echo '<table border="0" cellpadding="0" cellspacing="0" width="200">';
do {
echo '<tr><td width="100">'.$row_nested['size'].'</td><td width="100">'.$row_nested['amount'].'</td></tr>';
} while ($row_nested = $nested->fetch(PDO::FETCH_ASSOC));
echo '</table>';
echo '</td></tr>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC));
?>
</table>

Loop through database for a particular record and show results - PHP

i'm looking for a way to loop through the database and shows results in a html page, i'm actually creating a sorta fake email system for a little project.
so i have a table name "SENDS" with 5 columns ID, Mailtext, Touser, Subject, Fromuser.
what i wanna do is when user log in system connects to the database and select everything
from SENDS where touser='$email' -$email is defined when user logs in- and display it in a html div
<div class="oubx">
<div class="inbx">
<span class="from"></span>
<span class="subject"></span>
<span class="mailtext"></span>
</div>
</div>
.oubx {
height:27px; width:800px;
border:1px solid black;
margin-top:;
margin-left:80px;
float:left;
background-color:white;
}
.inbx {
height:22px; width:700px;
border:1px solid black;
margin-top:1px;
margin-left:45px;
background-color:white;
font-family:sans-serif;
font-weight:bold;
font-size:16px;
color:#808080;
float:left;
}
from of course tells whos it from
subject is subject
mailtext is what the mail is (it's hidden of course jQ will take care of it once clicked)
i have used mysqli_num_rows, mysqli_fetch_array, for loops, foreach etc but i just can't seem to get my head around it i'm having a hard time figuring out how to do it setp by steps or what the step is. please help :) thanks.
$connectDB = mysqli_connect("host","root","","db");
$touser = mysqli_query($connectDB, "select * from sends where touser='$email'");
$to_numrows = mysqli_num_rows($touser);
$to_fetch = mysqli_fetch_array($touser);
//printing of html code = how many rows
$ib = '<div class="oubx"><div class="inbx"><span class="from">'.$value.'</span><span class="subject">'.$value.'</span></div></div>';
for ($i = 0; $i < $to_numrows; $i++) {
echo $ib;
}
the rest is work in progress..
Try this,
$connectDB = mysqli_connect("host","root","","db");
$touser = mysqli_query($connectDB, "select * from sends where touser = '$email'");
$all_rows = mysqli_fetch_all($touser, MYSQLI_ASSOC);
$ib = '';
foreach($all_rows as $row) {
$ib .= '<div class="oubx">'
. '<div class="inbx">'
. '<span class="from">' . $row['Fromuser'] . '</span>'
. '<span class="subject">' . $row['Subject'] . '</span>'
. '</div>'
. '</div>';
}
echo $ib;
1- mysqli_fetch_all will fetch all result row into a PHP array
2- We loop through it with foreach (no need to know the rows count)
3- Foreach row, we append the HTML to the $ib intially set to empty string.
Hope it helps.
put the query result in a variable:
while ($row = $touser->fetch_array()) {
$rows[] = $row;
}
and iterate it with a loop:
foreach ($rows as $row) {
/* show appropriate html here */
}

php query - Background color changes

What I want is to change the color of a cell in a table based on the value that is returned by the query.
what I have done is this --
In the style
.priority_1, priority_-1, priority_0{
background-color: green;
color:green;
}
.priority_4, .priority_5, .priority_6, .priority_7, .priority_-4, .priority_-5, .priority_-6, .priority_-7{
background-color: red;
color:red;
}
and in the body - cell
<?php
$result = mysqli_query($con,"SELECT SHOP, FORMAT(VARMP,0) AS value FROM recordstable WHERE SHOP='1' AND Month='1' AND Type='TCheck'");
while($row = mysqli_fetch_array($result)) {
$priority = $row['value'];
echo "<td class=\"priority_{$priority}\"><center>";
echo $priority . "";
}
?>
</td>
this gives me what i want however, what if the value falls outside the range - if i get a value of 43 I want it red. but the .priority will only chnage to red for 7 to -7. how can i do a range easy easy style. without doing priority 1 - 100 plus an minus.
No need to create that many classes. If I've understood correctly, you probably need something like:
CSS:
.priority_green{
background-color: green;
color:green;
}
.priority_red{
background-color: red;
color:red;
}
PHP:
while($row = mysqli_fetch_array($result)) {
$priority = $row['value'];
$class = 'green';
if($priority >= -7 and $priority <= 7){ $class = 'red'; } //from 7 to -7 only
echo "<td class=\"priority_$class\"><center>";
echo $priority . "";
//don't forget to close <center> and <td> and you also don't have rows - just a note
}

CSS / PHP / MySQL - Display results into 3 columns

I'm trying to display the results of my query into a three columns for each row returned.
The setup is 3 divs all floating left inside one large wrapper. Easy enough, yeah?
#wrapper {width: 650px;}
#left {width: 200px; float: left;}
#middle {width: 200px; float: left;}
#right {width: 200px; float: left;}
Results displayed like:
LEFT | MIDDLE | RIGHT
LEFT | MIDDLE | RIGHT
LEFT | MIDDLE | RIGHT
LEFT | MIDDLE | RIGHT
Only now, I have this mysql associative query I want to display the results of in each column.
To be simple, I have Column A that needs to be in the left div.
Columns B through Y in middle div.
Column Z in right div.
Here's my query:
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
if ($col == "Column A") {
//How to get this in left div?
}
if ($col != "Column A" && $col != "Column Z") {
//How to get this in middle div?
}
if ($col == "Column Z") {
//How to get this in right div?
}
}
}
I'm really not sure where to even start.
Always try seperating the view (HTML) from the actual code. You might want to read a bit about the MVC arhitecture. It might seem hard to understand at first, but trust me - it's worth learning how to use it.
<?php
$column = array(
'A' => array(),
'B' => array(),
'Z' => array()
);
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
if ($col == "Column A") {
$column['A'][] = $row;
}
if ($col != "Column A" && $col != "Column Z") {
$column['B'][] = $row;
}
if ($col == "Column Z") {
$column['Z'][] = $row;
}
}
}
?>
<style type="text/css">
div {width:200px;float:left}
</style>
<!-- 1st column -->
<div><?php foreach ($column['A'] AS $row) { ?>...<?php } ?></div>
<!-- 2nd column -->
<div>..</div>
<!-- 3rd column -->
<div>..</div>
Cheers!
You have quite many options here. But as i would do this is to make 3 or 1 array(s) then in my template iterate them in html you got there.
Something like:
$col_left = array();
$col_mid = array();
$col_right = array();
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
if ($col == "Column A") {
$col_left[] = $val;
}
if ($col != "Column A" && $col != "Column Z") {
$col_mid[] = $val;
}
if ($col == "Column Z") {
$col_right[] = $val;
}
}
}
Then just in html loop those and your done. There's many more options to go, but this would be from the top of my head.
Then in html:
<div id="left">
<?php
foreach($col_left as $result){
echo $result.'<br/>';
}
?>
</div>
Something like that, ofc you can add checks for empty etc. there.
I would do it slightly autonomously, taking your current identifiers into account. I've just dumped all of the content into an array, and joined it with line breaks at the bottom. My example might be a little too general, but it certainly gets the job done, and tweaks are completely possible :)
<?
$columns = array(
'left' => array(),
'middle' => array(),
'right' => array()
);
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
if ($col == "Column A") {
$columns['left'][] = $val;
} elseif ($col == "Column Z") {
$columns['right'][] = $val;
} else {
$columns['middle'][] = $val;
}
}
}
?>
<div id="wrapper">
<? foreach($columns as $column => $value_array) { ?>
<div id="<?= $column ?>">
<?= join("<br />", $value_array) ?>
</div>
<? } ?>
</div>
I did this exact thing, but I put the result into a table. I used the modulus function with a helper counter variable.
if (($artisttablecount % 3) == 0){
echo "</tr><tr>";
}
I'm not sure how to do it with the divs, but the mod function may help. Full code below.
//QUERY
$artisttable = mysql_query("SELECT DISTINCT * FROM records GROUP BY artist ORDER BY artist ASC");
//HELPER VAR FOR PRINTING IN 3 ROWS
$artisttablecount=0;
//LOOP THROUGH RESULTS
while($row = mysql_fetch_array($artisttable)){
//MAKES TABLE 3 COLUMNS
if (($artisttablecount % 3) == 0){
echo "</tr><tr>";
}
$current=$row['Artist'];
$artcount = mysql_num_rows(mysql_query("SELECT * FROM records WHERE artist = '$current'"));
$spaceless = str_replace(" ", "%20", $row['Artist']);
echo "<td><a href=inventory.php?dec=0&format=0&art='" . $spaceless . "'>" . $row['Artist'] . "</a> ($artcount)</td>";
$artisttablecount++;
}
?>

PHP foreach loop (output into CSS)

If have an admin area where users can select a category name and an associated color to match it. There are 10 options (i.e. 10 categories, 10 colors)
This then gets outputted to the header to control category colors:
So for example,
$cat1 = get_option('catname1');
$col1 = get_option('col1');
$cat2 = get_option('catname2');
$col2 = get_option('col2');
and so on until 10. These are then outputted to CSS as follows (if the user has inputted anything on the admin panel):
if($cat1){echo "
.".$cat1"{ color:".$col1." !important; }
.".$cat1." { background-color:".$col1." !important; }" };
How would I combine these statements in a foreach (basically to go from cat1 to cat10)?
You can use a for loop:
for ($i=1; $i<11; $i++) {
$cat = get_option('catname' . $i);
$col = get_option('col' . $i);
if ($cat) {
echo ".$cat { color: $col !important; }
.$cat { background-color: $col !important; }";
}
}

Categories