i have this php mysql query
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$pro = mysql_fetch_assoc($product);
?>
Now that query will return 6 products from database and what i want to do is echo 3 products inside a <div> and the other 3 products inside another <div> like this
<div class="first-3>
///Here i want to echo 3 products from the query from 1-3
<?php echo $pro['title']; ?>
</div>
<div class="second-3>
///Here i want to echo the rest 3 products of the query from 4-6
<?php echo $pro['title']; ?>
</div>
<?php
$num = 6;
$product = mysql_query('SELECT * FROM products LIMIT $num');
$firstDiv = "";
$secondDiv = "";
$i = 0;
while ($pro = mysql_fetch_assoc($product)) {
if ($i < ($num /2)) {
$firstDiv .= $pro['title'];
}
else {
$secondDiv .= $pro['title'];
}
$i++;
}
?>
And:
<div class="first-3>
<?php $firstDiv ?>
</div>
<div class="second-3>
<?php $secondDiv ?>
</div>
Iterate and output the values.
<?php
$product = mysql_query('SELECT * FROM products LIMIT 6 ');
$i = 1;
echo '<div class="first-3">';
while ( $pro = mysql_fetch_assoc($product) ) {
if ($i === 3) {
echo '</div><div class="second-3">';
}
echo $pro['title'];
$i++;
}
echo '</div>';
?>
Note that it's not safe to use mysql_query, you should be using mysqli or preferrably PDO.
mysql_fetch_assoc is used to retrieve a row in the resultset.
Doc: http://php.net/manual/es/function.mysql-fetch-assoc.php
A loop is required to iterate on each row.
A very simple example:
// Get a collection of 6 results
$products = mysql_query('SELECT * FROM products LIMIT 6 ');
// iterate over the 6 results
$i=0;
echo '<div class="first-3>';
while ($pro = mysql_fetch_assoc($products)) {
$i++;
// Print an item
echo $pro["title"];
// If 3 items are printed end first div and start second div
if($i==3){
echo '</div><div class="second-3">';
}
}
echo '</div>';
// Free the collection resources
mysql_free_result($products);
Just set up a counter to divide in groups of 3:
$count = 0;
while (...)
{
// your code
$count++;
if ( ($count % 3) === 0 )
{
echo '</div><div class="...">';
}
}
Please note that the mysql_* functions are deprecated and you should switch to PDO or mysqli.
$product = mysqli_query($conn, 'SELECT * FROM products LIMIT 6 ');
$results = array();
while($pro = mysqli_fetch_assoc($product)) {
$results[] = $pro;
}
echo '<div class="first-3">';
for($i = 0; $i < 3; $i++) {
echo $results[$i]['title'];
}
echo '</div><div class="second-3">';
for($i = 3; $i < 6; $i++) {
echo $results[$i]['title'];
}
echo '</div>';
Everytime you get the multiple of 3, ($k % 3 == 0) you will increment the flag variable, you can do then some conditions with the variable flag, i used here iterators because the hasNext() beauty.
Example
$pro = array(1, 2, 3, 4, 5, 6);
$flag = 0;
$pro = new CachingIterator(new ArrayIterator($pro));
foreach ($pro as $k => $v) {
// if multiples 3
if ($k % 3 == 0) {
$flag++;
if ($flag == 1) {
echo '<div class="first-3" style="border:1px solid black;margin-bottom:10px;">';
} else if ($flag == 2) {
echo '</div>'; // Closes the first div
echo '<div class="second-3" style="border:1px solid red">';
}else{ // if you have more than 6
echo '</div>';
}
}
// insert Data
echo $v . '<br/>';
if (!$pro->hasNext())
echo '</div>'; // if there is no more closes the div
}
Related
I have 11 news then i want to display like
first column need only one news
second column need 5 news
third column need the rest of 5 news
I tried this but no luck, it shows first column and second column and the rest outside column
$rows = array(
'Title1',
'Title2',
'Title3',
'Title4',
'Title5',
'Title6',
'Title7',
'Title8',
'Title9',
'Title10',
'Title11',
);
$total_rows = count($rows);
$total_cols = $total_rows - 1;// remove first one for the first column
$left_column = ceil($total_cols / 2);
$right_column = $total_cols - $left_column;
$i = 0;
echo "<div class='row'>";
foreach ($rows as $row) {
$i++;
if ($i == 1) {
$class = "primary_post";
echo "<div class='col-md-4 main'>";
} elseif ($i <= $left_column) {
$class = "other_post";
echo "<div class='col-md-4 left'>";
} elseif ($i == $right_column) {
$class = "other_post";
echo "<div class='col-md-4 right'>";
} else {
$class = "other_post";
}
echo "<div class='card {$class}'>$i</div>";
if ($i == 1 || $i == $left_column || $i == $right_column) {
echo "</div>";
} else {
echo "";
}
}
echo "</div>";
The last echo "</div>"; supposed to be in the FOR loop not outside of it.
Also, you can split the array into chunks;
$firstColumn = array_splice($rows,0,1);
$secondColumn = array_splice($rows,0,5);
Rest are in the $rows variable.
So instead of dealing with ifs in for loops, you can use 3 different loops and list items in desired HTML objects.
Suppose I have 10 records, and 2 different classes namely c1, c2
<div class="c2">..content..</div>
<div class="c2">..content..</div>
<div class="c1">..content..</div>
<div class="c1">..content..</div>
<div class="c2">..content..</div>
<div class="c2">..content..</div>
<div class="c1">..content..</div>
<div class="c1">..content..</div>
<div class="c2">..content..</div>
<div class="c2">..content..</div>
i want the if else condition where class order needs to maintained like c2,c2,c1,c1,c2,c2,c1,c1,c2,c2.....so on
foreach(x as y){
if() {
<div class="<?php echo $class1;?>">..content..</div>
} else {
<div class="<?php echo $class2;?>">..content..</div>
}
class order should be c2,c2,c1,c1,c2,c2,c1,c1,c2,c2.....so on
Check the page url http://themesflat.com/html/nah/portfolio-creative.html
You can use a bitwise operator (&) here, and with 2 and this will toggle the class...
$i = 0;
foreach($x as $y){
if($i & 2) {
$class = "1";
} else {
$class = "2";
}
echo "<div class=$class>..content..</div>";
$i++;
}
I've extracted the echo out as this keeps it consistent, just have a variable for the class you want to have and put that in the if instead.
You can do it with a separate counter
$current = 'c2';
$count = 1;
for ($i = 0; $i < 10; $i++) {
echo '<div class="'. $current . '">..content..</div>';
if ($count == 2) {
$current = $current == 'c1' ? 'c2' : 'c1';
$count = 0;
}
$count++;
}
Demo: https://3v4l.org/7ftjg
This will of course work just as well in a foreach-loop.
Note: If it's only about styling the divs differently, you could do this in CSS alone. Here's a similar question and answer: nth-child: how to pick elements in groups of two
I'm pretty sure you can resolve the problem via css pseudo class :nth-of-type but if you prefered PHP you can try the following example.
<?php
$class_types = ['c2', 'c1'];
$records = array_fill(0, 10, '..content..'); // replace with your records
$records_length = count($records);
$html_output = '';
foreach ($records as $index => $item) {
$type = floor($index / $records_length * $records_length / 2) % 2;
$class = $class_types[$type];
$html_output .= sprintf('<div class="%s">%s</div>', $class, $item);
}
echo $html_output;
Try this code:
$counter = 1;
for($i=0;$i<=10; $i++){
if($counter==1 or $counter==2) {
echo '<div class="c1">..content..</div>';
} else {
echo '<div class="c2">..content..</div>';
}
if($counter==4){
$counter=0;
}
$counter++;
}
?>
How about we chunk the main array into an array or arrays of two
like
<?php
$chunked_array = array_chunk( $your_array , 2 );
// This will give us an array of 2 elements array
// now we will loop
for( $i = 1 ; $i < count( $chunked_array ); $++ ){
$contents = $chunked_array[$i];
foreach( $contents as $content ){
if ( $i%2 == 0 ){
//<div class="<?php echo $class1;?>">..content..</div>
}else{
//<div class="<?php echo $class2;?>">..content..</div>
}
}
}
using this way we have one loop and it will always be in a group of two even when your data grow or shrink
My code is below:
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
$i++;
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
}
echo '</div>';
}
}
portfolio_gallery();
I wanted to echo </div><div> for every after 9th item of the loop but every time I executed the code, the first echo only happened after 8 items instead of 9, but the rest was every 9th.
You have to increment
$i
after
if($i % 9 == 0)
follow the syntax example i worked out its working
<?php
$j=0;
for($i=0;$i<=50;$i++)
{
if($j==9)
{
echo $j.'hioiiiiiii<br/>'; //echo "</div><div>";
$j=-1;
}
$j++;
}
?>
Please try this :)
<?php
function portfolio_gallery() {
global $conn;
$query = $conn->query("SELECT codename, namegroup, features, title, showimage FROM portfolio ORDER BY id DESC");
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 0;
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 0){
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++;
}
echo '</div>';
}
}
declare $i = 1 and Write $i++ at the end of while loop.
if ($query->num_rows > 0) {
// output data of each row
echo '<div>';
$i = 1; // declare $i = 1 here
while($row = $query->fetch_assoc()) {
if ($row["showimage"]) {
if($i % 9 == 1){ // 10 , 19 ,28
echo '</div><div>';
}
echo '<a class="imgpop" href="images/portfolio/large/'.$row["codename"].'.jpg" rel="'.$row["namegroup"].'" title="'.$row["title"].' - '.$row["features"].'"><img src="images/portfolio/thumb/'.$row["codename"].'.jpg" alt="'.$row["title"].'" width="348"/><span class="imgpop-caption">'.$row["title"].'</span></a>';
}
$i++; // increment at end of the loop
}
echo '</div>';
}
I was able to solve it by modifying the condition:
So instead of: if($i % 9 == 0) {...}
I used: if($i!=0 && $i % 9 == 0) {...}
And also placing $i++ at the end of while loop.
I have the following code:
$max = 4;
$page = isset($_GET['page']) ? ($_GET['page']) : '1';
$init = $page - 1;
$init= $max * $init;
$strCount = "SELECT COUNT(*) AS 'total_mytable' FROM mytable";
$varstrCount = $crud->viewdatas($strCount);
$total = 0;
if(count($varstrCount)){
foreach ($varstrCount as $row) {
$total = $row["total_mytable"];
}
}
$result = "SELECT * FROM mytable ORDER BY id_mytable LIMIT $init,$max";
$varresult = $crud->viewdatas($result);
content of page:
<?php
if(count($varresult)){
foreach ($varresult as $res) {
?>
<h5><?php echo $res['title'] ?></h5>
<?php
}
}
?>
<?php
$max_links = 10;
$previous = $page - 1;
$next = $page + 1;
$pgs = ceil($total / $max);
if($pgs > 1 ){
if($previous > 0){
echo "<li><a href='".BASE_URL."/category/$previous' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>";
} else{
}
for($i=$page-$max_links; $i <= $pgs-1; $i++) {
if ($i <= 0){
}else{
if($i != $page{
if($i == $pgs){ //if end insert 3 dots
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li> ...";
}else{
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li>";
}
} else{
if($i == $pgs){ //if end insert 3 dots
echo "<li>".$i."</li> ...";
}else{
echo "<li>".$i."</li>";
}
}
}
}
if($next <= $pgs){
echo "<li><a href='".BASE_URL."/category/$next' aria-label='Next'><span aria-hidden='true'>»</span></a></li>";
}else{
}
}
?>
The result:
And I not understand the reason for the active number stay right off the paging menu
In the code I defined max-links for 10, but no show number 5 and if I define max links for 3 changes nothing , displays the same result as the image.
Thanks for any help
echo "<li>".$i."</li>";
on the above line add up a href, seems like you have css formatting for li>a because of which you are not getting the required formatting on only li. so for getting better formatting for all paging links current, prev, next. you need to add up a tags.
echo "<li><a>".$i."</a></li>"; //in your else part
This is a bit tricky to word but;
What I'm trying to do is add the style 'background-color: black;' to only some results in my query.
So, if i was to echo my results it would display like this;
1st result no style
2nd result black
3rd result black
4th result no style
5th result no style
7th result black
8th result black
9th result no style
10th result no style
My query
$getusers= $db->query("SELECT * FROM users");
while($users= $getusers->fetch_assoc()) {
$color = ??????????????? not sure
echo '<div style="background-color: ' . $color . ';">';
echo $users['username'];
echo '</div>';
}
Use a placeholder variable.
Follow the progression of $i in my example below.
$getusers= $db->query("SELECT * FROM users");
// Starting at 2 will cause "no style" to happen only once on first pass.
$i = 2;
while($users= $getusers->fetch_assoc()) {
// if $i is 3 or 4 value would be "black"
$rowBg = "background-color:black";
// Set to an empty string (no style) if $i is 1 or 2.
if($i <= 2) {
$rowBg = "";
}
$i++;
// Start over!
if($i > 4)
$i = 1;
echo '<div style="' . $rowBg . ';">';
echo $users['username'];
echo '</div>';
}
How about this:
$getusers= $db->query("SELECT * FROM users");
$r = 1;
while($users= $getusers->fetch_assoc()) {
$style = ($r == 2 || $r == 3) ? 'style="background-color: black"' : ''; // black for every 2nd & 3rd row
$r = ($r == 4) ? 1 : $r+1; // reset count to 1 when we get to 4
echo '<div $style>';
echo $users['username'];
echo '</div>';
}
$count = 1;
$getusers= $db->query("SELECT * FROM users");
while($users= $getusers->fetch_assoc()) {
$color = "#000000";
if($count == 2 || $count == 3){
echo '<div style="background-color: ' . $color . ';">';
if($count==3){
$count=0;
}
}
else{
echo "<div>";
}
echo $users['username'];
echo '</div>';
$count++;
}