How to apply if-else on css class in php code? - php

I am trying to apply if else condition in bootstrap class with php variable but its not working. My variable is getting result.
Below is my tbody where i am applying php code:
<div class="<?php '#count_rows#' <= '2')
{
echo 'middle_menu';
}
else
{
echo 'middle_menu1';
} ?>">
<table class="table_4">
<thead>
<tr>
<th class="th_11">Quantity</th>
</tr>
</thead>
<tbody>
#TABLE_BODY#
</tbody>
</table>
</div>
Below is my 2 css classes:
.middle_menu
{
margin-top: 40px;
padding-bottom: 200px;
}
.middle_menu1
{
margin-top: 40px;
}
I am fetching my variable from another page where i set this type of opening and closing variable with #.
Below is my code for your reference but i dont think that is an issue for me because i check this #count_rows# variable with print_r in my current page and it showing me correct result.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}

<?php $className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1'; ?>
<div class="<?php echo $className; ?>" />
You can create a test.php then run php test.php and you should see the result
<?php
// $count_rows = 1;
$count_rows = 3;
$className = $count_rows <= 2 ? 'middle_menu' : 'middle_menu1';
echo "<div class=\"$className\"/>\n";

<div class="<?php '#count_rows#' <= '2')
You are missing a keyword here and also some brackets (which should cause a fatal syntax error), Also you are comparing two different literal strings - surely one of the terms should be a PHP variable?
You can't read back stuff you've previously written to the output stream - you are confusing what is happening in HTML, CSS and PHP.
I think you mean...
<div class="<?php if ($form_fields['count_rows'] <= '2')
Comparing a number by casting it to a string is rather dangerous.
Personally I would do this:
<div class="<?php echo (2 <= $form_fields['count_rows'])
? 'middle_menu' : 'middle_menu1'; ?>">
Since you didn't mention that the script blew up in your face, I suspect there may be a lot of other issues.
foreach ($form_field as $key => $value){
$htmlContent = str_replace('#'.$key.'#', $value, $htmlContent);
}
This is very innefficient. Consider:
$find=array_keys($form_field);
foreach ($find as $index=>$term) {
$find[$index]='#' . $term . '#';
}
$htmlContent = str_replace($find, $form_feld, $htmlContent);

Related

How to make an php loop into an another php loop according to an array?

I am trying to nest a php loop into another php loop according to an php array. First loop will continue the loop according how many elements the array has and I want the second loop will continue according to the element. If the first element is 2 the user input repeat 2 times after that the second element is 3 the user input repeat 3 times. when all the elements are gone the loop stopped. but I don't know how to do it.
<body style="margin: 0 auto; width: 50%;">
<div class="input-field col s12">
<?php
$dolils = array("2","3","4");
$total_dolils = count($dolils);
for ($x = 1; $x <= $total_dolils; $x++) {
?>
<p class="blue-text" style="color: blue; font-weight: bold;"><?php echo $x; ?> নং দিনে দলিলের হিসাবঃ </p>
<?php
$z = 0;
for($y = 0; $y <= $dolils[$z]; $y++) {
?>
<p class="red-text" style="color: red; font-weight: bold;">দলিলের নাম্বার</p>
<input id="input_number" type="number" name="dolils_no[]" data-length="10">
<p>মোট পৃষ্ঠাঃ </p>
<input id="input_number" type="number" name="page[]" data-length="10">
<p>মোট লাইনঃ </p>
<input id="input_number" type="number" name="line[]" data-length="10">
<?php
$z++;
echo "<br/>";
echo $z;
echo "<br/>";
if($z >= end($dolils)){
die;
}
}
}
?>
</div>
</body>
Basic logic:
<?php
$content = '<div>';
$dolils = array (2, 3, 4);
foreach ($dolils as $dolil) {
for ($i = 1; $i <= $dolil; $i++) {
$content .= "<p>iteration {$dolil}/{$i} </p>";
}
}
$content .= '</div>';
// after all
echo $content;
bonus tip:
Stop mixing PHP and HTML like this is not comfortable, error pron and just ugly. Instead build HTML in one piece of PHP code or better get familiar with templating engines and/or MVC patterns.

3x3 table with random images - PHP

I'm new here and need some help. I'm doing a web development course and have an assignment I need a hand with.
Basically, I want to send a query that picks 9 random records, and show the result as a 3x3 table.
Here's my code so far:
<div id="productgrid">
<?php
$query = mysqli_query($conn, "SELECT * FROM products
ORDER BY RAND()
LIMIT 9");
?>
<h2>Featured Products</h2>
<table>
<?php
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<tr>
<div class="bigred">
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
</td>
</div>
</tr>
<tr>
<td>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
</td>
<div class="smallblack"
</tr>
<tr>
<td class = "smallblack">
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
</tr>
</div>
<?php } ?>
I can get it to generate the 9 random images but it puts them all directly under each other in one long column. Is there a way I can get them to display in 3 rows of 3?
I apologise if this is a dumb question, but I'm only starting out and appreciate the help.
Thank you :)
Pic attached as sample
<?php
// A counter which is incremented by one for each product row
// in the loop below.
$i = 0;
echo "<table>\n";
echo "<tr>\n";
while ($product = mysqli_fetch_array($query)) {
// Re-open HTML row, if $i is divisible by 3
if ($i++ % 3 == 0) {
echo "</tr><tr>\n";
}
// Escape the `src` attribute value as appropriate, according to the
// logic of your app. This is just a sample.
$img_src = htmlspecialchars($product['prod_img']);
echo <<<HTML
<td>
<div><img src="{$img_src}"/></div>
<div>{$product['prod_desc']}</div>
<!-- Put the rest of the fields here -->
</td>
HTML;
}
// Add cells for the rest of the columns (if any)
while ($i++ % 3 != 0) {
echo "<td></td>\n";
}
echo "</tr>\n";
echo "</table>\n";
?>
P.S.: I recommend using a template engine such as Smarty, or Twig. With the help of a template engine you can make the markup much more readable and maintainable.
You should change your table out put and use 3 <td> tags instead of just the one, like so...
<table>
<tr>
<?php
$counter = 0; // Needs to be outside of the loop...
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
<?php
// Check to see if you have looped through three times and close the <tr> tag.
if($counter % 3 === 0) {
echo '</tr><tr>';
}
$counter++
?>
</table>
If there is more than 9 images, then it will keep creating table rows and cells and you will need more logic to handle that, however, this should work for 9 images.
A more elegant way to handle this would be to use <div> tags and floats, but since you are already using a table, I formatted it as such.

CSS, PHP, mySQL Loop - change td colour depending on variable

Having an issue with assigning a td style class, depending on a variable from mySQL. I have a field called 'Avail' so when a seat is available, the seat should turn green. However, nothing is happening so far when I run it.
Have created the simple classes on the same html sheet but it doesn't seem to apply to any of the data.
CSS Class Definitions >>
<style>
.available {
background-color: green;
}
.unavailable {
background-color: red;
}
</style>
Code to show when style will be applied >>
<table>
<tr>
<th>Seats</th>
<tr>
<tr>
<?php
$c = 0; // Our counter
foreach($res as $row) {
$Avail = 'Avail';
$seatColour = null;
if($Avail == 0)
{
$seatColour = '.available';
} else
{
$seatColour = '.unavailable';
}
if($c % 20 == 0 && $c != 0) // If $c is divisible by $n...
{
// New row
echo '</tr><tr>';
}
$c++;
?>
<td style="$seatColour">
<form method="POST" name="Seating" action="SWG.php">
<?php echo $row['Seat']; ?> <?php echo $row['Avail']; ?>
<input type="checkbox" name="Seat[]" value="<?php echo $row['Seat'];?>"/>
</td>
<?php
}
?>
</tr>
</table>
Would really appreciate it if someone could point out where I'm wrong / how I'm assigning it incorrectly.
There seem to be several issues with your code:
$Avail = 'Avail';
$seatColour = null;
if($Avail == 0)
In the above code, you assign $Avail a string, and then you check whether it's zero. I'm assuming this is not deliberate. Maybe you want to assign the database value here (instead of a string)?
$seatColour = '.available';
You probably want to do $seatColour = "available". We're not in jQuery so no need for the dot.
td style="$seatColour"
You probably want to do <td class="<?php echo $seatColour ?>"> over here
Use class attribute instead of style in td and remove . from $seatColour as follows:
<table>
<tr>
<th>Seats</th>
<tr>
<tr>
<?php
$c = 0; // Our counter
foreach($res as $row) {
$Avail = 'Avail';
$seatColour = null;
if($Avail == 0)
{
$seatColour = 'available';
} else {
$seatColour = 'unavailable';
}
if($c % 20 == 0 && $c != 0) // If $c is divisible by $n...
{
// New row
echo '</tr><tr>';
}
$c++;
?>
<td class="$seatColour"><form method="POST" name="Seating" action="SWG.php">
<?php echo $row['Seat']; ?> <?php echo $row['Avail']; ?>
<input type="checkbox" name="Seat[]" value="<?php echo $row['Seat'];?>"/>
</td>
<?php } ?>
</tr>
</table>
instead of null try -1 .
or you put name/value for th.

While loop causing website to vanish

$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query) {
if ($i == "0") { ?><div style="width: 49%; float: left;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } elseif ($i == "1") { ?><div style="width: 49%; float: right;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } $i++; if ($i == "7") { end while; }
}
Why doesn't this code work? If I do it manually without database. You know, just thinking you're PHP and creating the code in HTML and CSS, it works. But as soon as you mix PHP to it, everything goes blank, entire website.
while ($row = mysql_fetch_assoc($sql_query) {
"PHP Parse error: syntax error, unexpected '{' in
As mentioned in comments, you are missing a closing parenthesis (rounded bracket) on your while condition, before the opening brace (squiggly bracket). This should read:
while ($row = mysql_fetch_assoc($sql_query)) {
However, you do have another obvious parse error at the end of your while loop. The following is invalid syntax:
if ($i == "7") { end while; }
This should read:
if ($i == "7") { break; }
"mix PHP and HTML like that" - just don't mix PHP and HTML like that... it's hard to read/maintain.
Regardless of syntax used (conventional or alternative (that Tero Kilkanen suggests) - which is intended to make this type of code easier to read) you simply should not be mixing PHP and output like this anyway, by dropping out/in of PHP parsing mode.
If you need to construct some HTML to be output later then build a string and echo this once at the end of your loop.
So, instead of this:
$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query) {
if ($i == "0") { ?><div style="width: 49%; float: left;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } elseif ($i == "1") { ?><div style="width: 49%; float: right;"><img id="lookup_designs_item_icon" src="img/designs/<?php echo $row["id"]; ?>.jpg" alt="<?php echo $row["resolution"]; ?> | <?php echo $row["artist"]; ?>"/></div>
<?php } $i++; if ($i == "7") { end while; }
}
Do something like this:
// HTML to be output
$htm = '';
$i = 0;
$sql_query = mysql_query("SELECT * FROM designs WHERE accessibility=`2` ORDER BY id DESC LIMIT 5");
while ($row = mysql_fetch_assoc($sql_query)) {
if ($i == "0") {
$htm .= <<<EOD
<div style="width: 49%; float: left;">
<img id="lookup_designs_item_icon" src="img/designs/{$row["id"]}.jpg" alt="{$row["resolution"]} | {$row["artist"];}"/>
</div>
EOD;
}
elseif ($i == "1") {
$htm .= <<<EOD
<div style="width: 49%; float: right;">
<img id="lookup_designs_item_icon" src="img/designs/{$row["id"]}.jpg" alt="{$row["resolution"];} | {$row["artist"];}"/>
</div>
EOD;
}
$i++;
if ($i == "7") {
break;
}
}
// Output HTML
echo $htm;
The code is now much easier to read at a glance and it quickly becomes obvious that there are further optimisations that can be made. For instance...
the only bit that seems to vary between your if blocks is the float: left / float: right part of your style attribute. So these could be combined.
$i is an integer, yet you are comparing it with a string in your if condition. This works, but is not "correct".
You don't appear to be doing anything in your loop when $i is 2, 3, 4, 5 or 6? So you should be breaking sooner. ie. simply else { break; } would seem to do the same thing?

php every sixth row add class

I have a mysql query which selects 18 items from the table, but I'd like it to add a class on every 6th item.
Here's my code:
$i = 0;
foreach ($this->Items as $item) {
if ($item->image) {
echo '<div class="storeImages"> <img src="/images/store/'.$item->image.'" width="113" height="153" border="0" alt="'.$item->name.'" title="'.$item->name.'" /> </div>';
};
$i++;
};
I've tried a couple of different things, but can't seem to get it working, basically on each 6th item, I want to add style="margin-right: 0px;" :)
if($i % 6 == 0){
//add class
}
Take a look at the arithmetic operators in the manual.
Have a look at the Mod function (%)
somthing like.
if($i % 6 == 0)
edit: beaten to it.
$style = '';
if ($i % 6 == 0) {
$style = ' style="margin-right: 0px;"';
}
echo '<div class="storeImages" ' . $style . '> <img src="/images/store/'.$item->image.'" width="113" height="153" border="0" alt="'.$item->name.'" title="'.$item->name.'" /> </div>';
Modulo is your friend.

Categories