Alternating CSS Style with multiple Mysql Results - php

I've got a site where someone searches for x product in their location and the site spits back a list of results.
if(isset($_POST['zip'])){
$qry="SELECT business_id FROM ".TBL_BUSINESS." WHERE zip LIKE '%".$_POST['zip']."%'";
$rs = mysql_query($qry);
$rec = array();
while(($row = mysql_fetch_array($rs)) !== FALSE ){
$rec[] = $row[0];
}
if(!empty($rec[0])){
echo "Products for this location<br/>";
foreach ($rec as $result)
{
$bid = $result;
$qry2 = "SELECT * FROM products WHERE business_id = '".$bid."'";
$rs2 = mysql_query($qry2);
$rec2 = mysql_fetch_array($rs2);
?>
<div class="norm">
<img src="admin/product/img/<?php echo $rec2['image']; ?>" height="40" width="40" />
<h3><?echo $rec2['name'];?> <?php echo $rec2['prodvalue']?></h3>
<div class="prodlistMeta">
<a class='view' href="product.php?id=<?php echo $rec2['id']; ?>">View Product</a>
<a class="print" href="#">Print</a>
</div>
</div>
<?php
}
}
else
{
echo "No Product is added for this location";
}
}
?>
What would be the best way to alternate <div class="norm"> with <div class="alt">?

keep a counter and use it's value modulo 2 to determine whether the class should be "norm" or "alt".
$rec2 = mysql_fetch_array($rs2);
$count++;
?>
<div class="<?php echo($count%2?"norm":"alt"); ?>">

I tend to use something like this:
$row = 0;
foreach ($rec as $result) {
$class = $row++ & 1 == 1 ? 'alt' : 'norm';
...
echo <<<END
<div class="$class">
...
END;
}
You can use curly braces to do the expression within the string but I generally prefer not to embed that kind of logic. It's (imho) a little harder to read. Plus the above gives you the opportunity to output it for debugging purposes more easily, etc.

if(some expression)
{
$class="norm";
}
else
{
$class="alt";
}
?>
<div class="<?php echo $class;?>">

set a counter on your output loop. Whenever the counter is even, set the class to normal, else set it to alternate.

Why not use modulus and a row id? Much simpler, no need for unnecessary variables
foreach ($rec as $rid => $result)
{
$bid = $result;
$qry2 = "SELECT * FROM products WHERE business_id = '".$bid."'";
$rs2 = mysql_query($qry2);
$rec2 = mysql_fetch_array($rs2);
?>
<div class="<?=($rid % 2 == 0) ? 'norm' : 'alt' ?>">
<img src="admin/product/img/<?php echo $rec2['image']; ?>" height="40" width="40" />
<h3><?echo $rec2['name'];?> <?php echo $rec2['prodvalue']?></h3>
<div class="prodlistMeta">
<a class='view' href="product.php?id=<?php echo $rec2['id']; ?>">View Product</a>
<a class="print" href="#">Print</a>
</div>
</div>
<?php
}

Widespread adoption of CSS 3 can't come soon enough: http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#structural-pseudos

Related

How do I show just the first image from mysql database in php

I have the following code. How do I show the first image in the database with index of 0 for the large image display at end of the code? Right now it is showing the last image in the database.
<div id="imgWheel" class="treatmentContainer">
<?php
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$product = $row["product"];
$room = $row["room"];
$style = $row["style"];
$tags = $row["tags"];
$src = $row["url"];
$dataid = $row["id"];
$imgClass = "";
if (in_array($src, $favourites)) {
$imgClass = " favourite";
}
echo "<div class='treatment$imgClass' data-url='$src' data-product='$product' data-room='$room' data-style='$style' data-tags='$tags' data-number='$dataid' id='pic_$dataid' >";
echo "<img src='$src' crossorigin='anonymous'/>";
echo "</div>";
}
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $src ?>" />
</div>
Your result set is alreadyx ordered by id, so you need only a variable, to be filled once with the first imageurl
<div id="imgWheel" class="treatmentContainer">
<?php
$bigpictureurl = "";
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$product = $row["product"];
$room = $row["room"];
$style = $row["style"];
$tags = $row["tags"];
$src = $row["url"];
$dataid = $row["id"];
if (empty($bigpictureurl)) {
$bigpictureurl = $src ;
}
$imgClass = "";
if (in_array($src, $favourites)) {
$imgClass = " favourite";
}
echo "<div class='treatment$imgClass' data-url='$src' data-product='$product' data-room='$room' data-style='$style' data-tags='$tags' data-number='$dataid' id='pic_$dataid' >";
echo "<img src='$src' crossorigin='anonymous'/>";
echo "</div>";
}
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $bigpictureurl ?>" />
</div>
You just need to update your SQL query, just add LIMIT 1. This will limit the result just to 1 record and as you have ORDER id ASC, it will show the first record of the given user (as per you it is 0).
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id ASC LIMIT 1;";
A quick and dirty solution is to save your first image in some separate variables, for example like this:
$isFirst = true;
$firstImageSrc = "";
$result = ....;
while (...) {
// set your $product, $room etc here
if ($isFirst) {
$isFirst = false;
$firstImageSrc = $src;
}
}
echo ...
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $firstImageSrc ?>" />
</div>
A much more elegant solution would be to create an array with all your images, so that you can separate your php from your html. I will refactor your code below, and fix your first image problem as well:
<?php
$images = [];
$idx = 0;
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$images[$idx]["product"] = $row["product"];
$images[$idx]["room"] = $row["room"];
$images[$idx]["style"] = $row["style"];
$images[$idx]["tags"] = $row["tags"];
$images[$idx]["src"] = $row["url"];
$images[$idx]["dataid"] = $row["id"];
$images[$idx]["imgClass"] = "";
if (in_array($src, $favourites)) {
$images[$idx]["imgClass"] = " favourite";
}
$idx++;
}
?>
<div id="imgWheel" class="treatmentContainer">
<?php foreach ($images as $image) { ?>
<div class='treatment<?=$image["imgClass"]?>' data-url='<?=$image["src"]?>' data-product='<?=$image["product"]?>' data-room='<?=$image["room"]?>' data-style='<?=$image["style"]?>' data-tags='<?=$image["tags"]?>' data-number='<?=$image["dataid"]?>' id='pic_<?=$image["dataid"]?>' >
<img src='<?=$image["src"]?>' crossorigin='anonymous'/>
</div>
<?php } ?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?=$images[0]["src"]?>" />
</div>
Since you have all of that in your WHILE statement, I assume you want to echo all those records. And then at the end show the 1st pic. So for the "Large Image Display," give this a try:
<div id="display">
$query = "SELECT * FROM images WHERE user = 0;";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC)
$src = $row["url"];
<img id="mainImage" src="<?php echo $src ?>" />
</div>
If you'd like less code, then save the value of $src inside your WHILE loop when user=0 into some other variable like $src2. And then your code simply becomes:
<img id="mainImage" src="<?php echo $src2 ?>" />

plus plus operator not working in php

<?php
$qry = mysql_query("select branch from branches");
while($row = mysql_fetch_array($qry)) {
$branch = $row['branch'];
$i=1;
?>
<div class="dropdown">
<input type="checkbox" id="drop<?php echo $i; ?>" />
<label for="drop<?php echo $i++; ?>" class="dropdown_button"><?php echo "$branch"; ?><span class="arrow"></span></label>
<ul class="dropdown_content">
<?php
$qry1 = mysql_query("select sub_dir from `$branch`");
while($row1 = mysql_fetch_array($qry1)) {
$sub_topic = $row1['sub_dir'];
?>
<li><?php echo "$sub_topic"; ?></li>
<?php
}
?>
</ul>
</div>
<?php }?>
In line number 9, you can see, inside 'label' tag, I am trying to increment the variable '$i' but of no use because at every call to next row from the table, the value of '$i' remains same i.e. '1'. Where I am doing wrong.
Another question: Is it possible to create id's at run time as I did in line 8, i.e 'drop1, drop2,...'. May be its foolish way of doing something but I am trying new things.
$i initialization will be before the while loop
$i=1;
while($row = mysql_fetch_array($qry)) {
$branch = $row['branch'];
Initialize $i before the loop begin
$i=1;
while($row = mysql_fetch_array($qry)) {
//while loop block
}

show only three records and then move to next line

This is a very basic problem but I am very new to PHP.
I need to show results in such scenario that only three records in same line then add <br /> and then on next line, same thing should happend. I am unable to make its logic and in a great trouble :(
Right now, I am just using the simple way i.e.
while($data = mysql_fetch_array($res_set)) {
?>
<div><?php echo $data['name']?><img src="images/<?php echo $data['image']?>" /></div>
<?php
}
this is my code
$cnt = 0;
while ($prd = mysql_fetch_array($res)) {
?>
<div class="imageRow">
<?php
$cat_id = $prd['cat_id'];
$sql = "select * from tbl_category where id = $cat_id";
$cat_res = mysql_query($sql);
$cat_data = mysql_fetch_array($cat_res);
$cat_name = $cat_data['name'];
?>
<div class="set">
<div class="single first">
<img src="<?php echo $ru ?>admin/product_images/<?php echo $cat_name ?>/large/<?php echo $prd['thumb_img'] ?>" style="height: 100px; width: 100px;" /><br />
Choose
</div>
</div>
</div>
<?php
$cnt = $cnt++;
if($cnt%3 == 0) {echo "<br />";}
}
//echo $cnt;
?>
any help will be appreciated.
Thanks
<div class="imageRow">
<?php
$i = 0;
while($data = mysql_fetch_array($res_set)) { ?>
<div>
<?php echo $data['name']; ?><img src="images/<?php echo $data['image']; ?>" />
</div>
<?php
$i++;
if($i % 3 == 0) {
echo '</div><div class="imageRow"><br />';
}
}
?>
</div>
Explanation:
Set the variable $i to a number, which will then be used to keep track of how many items you've written.
Then, within the while loop, increment $i ($i++), which is the same as $i = $i + 1; By doing this, you always know which item you're on - whatever the value of $i is. Some people choose to set it to 1 initially then increment at the very end - other like to set it to 0, and set it near the beginning - either is completely fine - whatever you need it to do / whichever way you like better.
Lastly, check if $i is evenly divisible by 3 (kind of like remainder - it's called "mod" and is represented by the percent symbol). If it is, then echo a line break.
Try this
<?php
echo "<div>";
while($data = mysql_fetch_attay($res_set)) {
?>
<div style="width:30%; float:left"><?php echo $data['name]?><img src="images/<?php echo $data['image']?>" /></div>
<?php
}
echo "</div>";
?>
Output
<div>
<div>1</div> <div>2</div> <div>3</div>
<div>1</div> <div>2</div> <div>3</div>
<div>1</div> <div>2</div> <div>3</div>
</div>
That's some super ugly code you have there. This will do what you need, and is cleaner.
<?php
$i=1;
while($data = mysql_fetch_attay($res_set)) {
$frame = '<div><img src="%s" /></div>';
printf($frame, $data['image']);
if($i % 3 == 0) { echo '<br />'; }
$i++;
}
Also, <img> elements are already block elements to begin with, you really don't need to wrap another <div> around them.

:nth child not working in jquery

I am trying to insert a <br clear="all" /> after each fifth div. Below is how I create the divs in php and then I try to use jquery to seperate them. But it is not working! Any help would be greatly appreciated! Thanks in advance!
PHP:
$get = mysql_query("SELECT * FROM Products $cate ") or die(mysql_error());
while($row= mysql_fetch_array($get)){
$pname = $row['Pname'];
$image = $row['Pimage'];
$id = $row['ID'];
?>
<div class="productCat"><img src="../products/<?php echo $image ?>" width="100" height="100" /><br /><?php echo $pname ?></div>
<?php
}
?>
JQUERY:
$(".productCat :nth-child(5)").append("<br clear='all'/>");
There isn't supposed to be a space after .productCat.
Also, why not just do it in the PHP? Just add a counter:
$count=0;
while($row= mysql_fetch_array($get)){
$count++;
$pname = $row['Pname'];
$image = $row['Pimage'];
$id = $row['ID'];
?>
<div class="productCat"><img src="../products/<?php echo $image ?>" width="100" height="100" /><br /><?php echo $pname ?></div>
<?php
if($count%5==0)
echo "<br clear='all'/>";
}
?>
put the space out between class selector and nth-child :
$(".productCat:nth-child(5)").append("");
The problem is that it's looking for the multiple-of-five-th children of .productCat, because of the extra space. EDIT: Actually, it's only looking for the 5th child of .productCat, because you left the n out.
Besides, what's wrong with:
/* CSS: */
.productCat:nth-child(5n+1) {clear: left;}
This CSS-only solution is far more efficient.
Why not doing it in PHP ? If you use jQuery, people without javascript won't have your "br" ...
<?php
$get = mysql_query('SELECT * FROM Products '.$cate) or die(mysql_error());
$i=0;
while($row = mysql_fetch_array($get)){
$i++:
?>
<div class="productCat"><img src="../products/<?php echo $row['Pimage']; ?>" width="100" height="100" /><br /><?php echo $row['Pname']; ?></div>
<?php
if($i == 5){
echo '<br clear="all" />';
$i=0;
}
}
?>

How do I output two fields in PHP?

I have a database that has two fields: current, and previous.
Here is the code:
<?
$username="*****";
$password="*****";
$database="******";
mysql_connect(localhost,$username,$password) or die("Unable to connect to server");
mysql_select_db($database) or die( "Unable to select database");
$query='SELECT * FROM tasks WHERE current=1 OR previous=1';
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
It then output it and manipulate it like this:
<div class="tasklist">
<div class="currentProject">
Current Project:
</div>
<?
$i=0;
while ($i < $num) {
$title=mysql_result($result,$i,"Title");
$link=mysql_result($result,$i,"Weblink");
$description=mysql_result($result,$i,"Description");
$id=mysql_result($result,$i,"ID");
$howto=mysql_result($result,$i,"howto");
$blogpost=mysql_result($result,$i,"blogpost");
$done=mysql_result($result,$i,"done");
$current=mysql_result($result,$i,"current");
$previous=mysql_result($result,$i,"previous");
if ( $current == 1 ) {
$current = "current";
} else {
$current = "";
}
if ( $previous == 1 ) {
$previous = "previous";
} else {
$previous = "";
}
?>
<div class="<? echo $done ?> task <? echo $id ?>" id="<? echo $current.$previous ?>">
<div class="titleWrapper">
<div class="title">
<a class="article" href="<? echo $link ?>"><? echo $title ?></a>
</div>
</div>
</div><BR>
<?
$i++;
}
echo "</div>";
?>
The problem is that since previous comes before current in the database, it outputs previous and then current.
Question:
How do I make sure to output current first, and then previous?
Instead of outputting both directly, store them until you actually have both, and then output both in the correct order.
Just append this to your query order by previous.
It must work as long as current task registry has previous=0 and previous task registry has previous=1.

Categories