excluding a row from a mysql database outputting - php

Every third element extracted from the database will output in the large box, while every other element will output in the small box. What I need it to do is exclude the third element when the small box is outputted. Any ideas on how to accomplish this?
while($array = mysql_fetch_assoc($result)) {
if($i % 3 == 0) {
// large box
echo '<div class="box" style="width: 692px; height: 218px">' . $array['feedName'] . '</div>';
}
// small box
echo '<div class="box" style="width: 246px; height: 218px">' . $array['feedName'] . "<br></div>";
// exclude the third element
$i++;
}
}

If I understand what you want correctly (each third item is in the large box and kept out of the small box), you just use an else clause in your if.
while($array = mysql_fetch_assoc($result)) {
if($i % 3 == 0) {
// large box
echo '<div class="box" style="width: 692px; height: 218px">' . $array['feedName'] . '</div>';
}
else {
// small box
echo '<div class="box" style="width: 246px; height: 218px">' . $array['feedName'] . "<br></div>";
}
$i++;
}

divide by 6 and get the remainder (%)
if (remainder == 0 or 3) {
large box
} else if (remainder == 1 or 5) {
small box
}

Related

How to retrieve specific values from array with multiple PHP for loops?

I have been working on trying to retrieve specific results from a PHP for loop without success.
My objective is to run a loop on an array and to pull the specific value each time if it exists within the array. I am able to run the first loop and retrieve a value, however, when I run the second for function it retrieves the exact same number. I haven't been able to figure out why. E.g. The first loop returns the value of 6, but so does the second loop. I am trying to retrieve 6 if it exists from the first loop and 7 if it exists in the second loop. 7 is located in the array, so it should return 6 in the first for statement and 7 on the second.
Here is what I have done so far:
for ($i = 0; $i < count($final_data); $i++) {
$check_sector = $final_data[$i]['sector'];
$check_image = $final_data[$i]['image'];
if($final_data[$i]['sector'] == 6){
echo "<div id='6' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
. "<div id='ss6' style='position: absolute; width: 100px; height: 100px; background-image: url(" . $check_image . ");'></div>"
."<div id='s6' class='overlay' ></div></div>";
break;
}else{
echo "<div id='6' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
."<div id='s6' class='overlay' ></div></div>";
break;
}
}
for ($i = 0; $i < count($final_data); $i++) {
$check_sector = $final_data[$i]['sector'];
$check_image = $final_data[$i]['image'];
if($final_data[$i]['sector'] == 7){
echo "<div id='7' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
. "<div id='ss7' style='position: absolute; width: 100px; height: 100px; background-image: url(" . $check_image . ");'></div>"
."<div id='s7' class='overlay' ></div></div>";
break;
}else{
echo "<div id='7' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
."<div id='s7' class='overlay' ></div></div>";
break;
}
}
When you get to the second foreach loop, it’s hitting the first element in the array first.
So it’s saying is 6==7? No, so it goes to the else echo statement.
Then you have a break so it gives up and never checks the second element in the array which is the 7.

dynamic grid using php and bootstrap

I want to make a dynamic grid using php and bootstrap.
For example
Case 1 => If i have total 6 records then row 1 contain col-md-4 grids and row 2 contain col-md-4 grids
Case 2 => If i have total 5 records then row 1 contain col-md-4 grids and row 2 contain col-md-6 grids
Case 3 => If i have total 4 records then row 1 contain col-md-4 grids and row 2 contain col-md-12 grids
How to do that i have no idea, any solution?
<?php foreach($Banners as $i=>$DATA){
if($count%3==1){
echo "<div class='row'>";
$lgclass = "col-lg-4";
}
if($count%4==0){
$lgclass = "col-lg-6";
}
if($count%5==0){
$lgclass = "col-lg-6";
}
?>
<div class="<?php echo $lgclass;?> col-xs-12 col-sm-12" <?php echo $count;?>>
<h2 class="section-title" > </h2>
<a href="http://mymegarealty.net/index.php?option=com_jointeam">
<div class="full-width">
<img src="<?php echo $Imageurl;?>" class="img-responsive" style="height:250px;;display:unset;">
</div>
</a>
</div>
<?php
if($count%3==0){
echo "</div>";
}
$count++;} ?>
it would be better a recursive solution, if you want you can do it. I wrote you at the beginning the logic if I follow an example overturned on your needs. my logic was the procedural one.
<?php
/*
logic
while myElements !=0
if myElements > 2
dispay row whith 3 elements
myElements remove firs 3
else if myElements == 2
dispay row whith 2 elements
myElements remove firs 2
else if myElements == 1
dispay row whith 1 elements
myElements remove firs 1
end while
*/
// init my data
$data=[];
$element=5;
for($i=0;$i<$element;$i++){array_push($data,$i);}
var_dump($data);
// do code
function displayElement($data, $classAdd){
echo "<div class='".$classAdd."'>";
echo $data; // your cell
echo "</div>";
}
while (sizeof($data)!=0){
if (sizeof($data)>2){
echo "<div class='row'>";
displayElement($data[0],"col-lg-4");
displayElement($data[1],"col-lg-4");
displayElement($data[2],"col-lg-4");
echo "</div>";
$data=array_slice($data,3);
}elseif (sizeof($data)==2){
echo "<div class='row'>";
displayElement($data[0],"col-lg-6");
displayElement($data[1],"col-lg-6");
echo "</div>";
$data= array_slice($data,2);
}elseif (sizeof($data)==1){
echo "<div class='row'>";
displayElement($data[0],"col-lg-12");
echo "</div>";
$data= array_slice($data,1);
}
}
You should be able to simply achieve this with flex. But with bootstrap try to use recursion: small example below
<?php
$elements = [1, 2, 3, 4];
function displ(&$el, $out = "") {
if (count($el) === 0) {
return $out;
} elseif (count($el) > 3) {
$i = 0;
foreach ($el as $k=>$v) {
$out .= "<div class=\"col-md-4\">" . $v . "</div>";
unset($el[$k]);
$i++;
if ($i === 3) {
return displ($el, $out);
}
}
return displ($el, $out);
} elseif (count($el) < 3) {
foreach ($el as $k=>$v) {
$out .= "<div class=\"col-md-" . 12 / count($el) . "\">" . $v . "</div>";
unset($el[$k]);
}
return $out;
}
}
echo displ($elements);

PHP script printing div

Is there a possible way to multiply code and print it out using PHP?
I am trying to make a script that checks users and draws a line depending on count.
CSS Code
#outer { // gray backround - always on.
background-color: #401800;
width: 150px;
height: 6px;
}
.inner { // used if there's less than 100 ppl online
width: 1px;
height: 6px;
display:block;
float:left;
}
.bigger { // used if 100+ people are online
width: 10px;
height: 6px;
display:block;
float:left;
}
}
.bigger.trys { // color for small px
background-color: green;
}
.inner.vienas { //color for big px
background-color: green;
}
PHP code ($rows = counted users):
if {$rows <= "0"
echo"<span class="inner vienas"></span>"; //draws small 1px width bar
}
elseif{$rows >= "10"
echo"<span class="inner vienas"></span><span class="inner vienas"> </span>"; // count =10 or greater - draws x2 bars.
}
elseif{$rows >= "100" // if users are 100 OR more counts new variable
$padala = $rows/10 //variable is users/10
echo 10*"<span class="bigger trys"></span>") //i want to print this out as 1px each 10 users
}
else {
echo "Script error";
}
Is there a way to do that?
Basicly you have lot of syntax error.
First, if statement need a condition:
Wrong:
if {
$rows <= "0"
echo"<span class="inner vienas"></span>"; //draws small 1px width bar
}
Correct (i don't know if $row have an integer or string, but if you use numbers, the correct is to storage an integer):
if ($rows <= 0) {
echo '<span class="inner vienas"></span>';
}
Second, echo:
You have an error with double quote marks when inserting HTML code, you don't have to cut the echo
Wrong:
echo"<span class="inner vienas"></span>";
Correct (using simple quotes):
echo '<span class="inner vienas"></span>';
Another error is that echo*10, you need to use a for loop.
for($i=0; $i<=9; $i++) {
echo '<span class="bigger trys"></span>';
}
Btw, I don't understand what you want, but the correct maybe is this:
if ($rows <= 0) {
echo '<span class="inner vienas"></span>';
} else if ($rows >= 10) {
echo '<span class="inner vienas"></span><span class="inner vienas"> </span>';
} else if ($rows >= 100) {
$padala = $rows / 10
for($i=0; $i<=9; $i++) {
echo '<span class="bigger trys"></span>';
}
} else {
echo "Script error";
}
Here you can read more about if statements and for:
PHP Manual - If Statements
PHP W3Schools - For loops
Without knowing more about your data, I'm not sure how I would go about doing what you want to accomplish. However, Here is your above code with the syntax fixes.
The conditions in the if statements should be wrapped in Parentheses, and the double quotes in the strings after the the echo functions should be escaped
if ($rows <= "0") {
echo"<span class=\"inner vienas\"></span>"; //draws small 1px width bar
} elseif($rows >= "10") {
echo"<span class=\"inner vienas\"></span><span class=\"inner vienas\"> </span>"; // count =10 or greater - draws x2 bars.
} elseif($rows >= "100") { // if users are 100 OR more counts new variable
$padala = $rows/10 //variable is users/10
echo 10*"<span class=\"bigger trys\"></span>") //i want to print this out as 1px each 10 users
} else {
echo "Script error";
}

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>

Separate MySQL results into Divs using while loop

Just beginning PHP to bear with me.
Results I'm trying to achiever:
I have a table of YouTube URL's and MetaData.
Trying to build this:
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
Two videos per slide, then I'm going to paginate through results using Deck.js.
I suspect I'm going about this completely the wrong way, not that experienced at programmin g logic;
while($data = mysql_fetch_array($result)) {
for ($counter = 1; $counter<=2; $counter++) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
/* If Video 1, increment counter for 2nd video */
if ($counter == 1) {
$counter++;
}
/* If Video 2, close div and reset counter */
else if ($counter == 2) {
echo "</div>";
$counter = 1;
}
/* If error break out */
else {
echo "</div>";
break;
}
}
}
Basically trying to nest loops to keep track of how many videos per div and start a new one when a div has two.
I've tried a few different ways, this being the latest. Results in:
<div class="slide">
<iframe></iframe>
<div class="slide>
<iframe></iframe>
Hit the blank wall now, not sure what to try next. Willing to use/learn any method to accomplish the results, just not sure where to go at this point.
Cheers.
You could remove the second loop all together using the % operator (modulus). The idea is that a % b === 0 then the number a was evenly divisible by b. Using this, you can easily check for even or odd or every Nth row.
$k = 1;
echo "<div class=\"slide\">";
while($data = mysql_fetch_array($result)) { // you should really change to mysqli or PDO
if($k % 3 === 0){
echo "</div>";
echo "<div class=\"slide\">";
}
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
$k++;
}
echo "</div>";
Put the echo <div> before the for loop (still inside the while loop) and the </div> after the for loop
In your while loop you're retrieving just one row, but then you're iterating over it twice with a nested loop. Do away with the inner loop and just use a flip-flop variable to track left and right. I think this will do what you want:
$left=true; // track whether we're emitting HTML for left or right video
while($data = mysql_fetch_array($result)) {
if ($left) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
}
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
if (!$left) {
echo "</div>";
}
$left = !$left; // invert $left to indicate we're emitting the right iFrame
}
// end of loop. If we had an odd number of
// videos, tidy up the HTML
if (!$left) {
echo "</div>";
}
PHPFiddle
<?php
$x = 10;
$counter = 0;
while($x > 0)
{
if($counter != 0 && $counter % 2 == 0)
{
echo "ENDOFSLIDE</br>";
}
if($counter == 0 || $counter % 2 == 0)
{
echo "SLIDE</br>";
}
echo "iframe => $x </br>";
$x--;
$counter++;
}
echo "ENDOFSLIDE";
?>
It won't work because the for loop is inside the fetch loop for the SQL data. The second iteration of the for loop does not have a new SQL row. A better solution would be to capture the common column that identifies the two videos (the title) and generate a new div whenever that value changes. Try something like this, which will work for any number of SQL rows with the same title. This will also give proper results if the SQL query returns no rows and will handle the potential of a title with only one URL - which could get ugly if you merely flip-flop and end up with URLs on the wrong title. Of course, as in your current solution, your SQL query must ORDER BY VIDEO_TITLE so the rows are adjacent. I didn't run it, but should be close.
$lastTitle = "";
$n = 0; //count SQL rows processed
while($data = mysql_fetch_array($result)) {
// See if the title changed from last
if( $data['VIDEO_TITLE'] != $lastTitle ) {
// if we processed any rows, must end the current div before starting a new one
if( $n > 0 )
echo "</div>";
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
//save the title as last title
$lastTitle = $data['VIDEO_TITLE'];
}
$n++; //count the SQL row
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
}
if( $n > 0 )
echo "</div>";

Categories