How to make a variable loop itself inside another loop? - php

It might be confusing and a bit difficult. I have a $fcomm variable that holds values as an array. This variable $fcomm is then assigned to an 'echo div' into another foreach loop. What I need is to make $fcomm loop itself while it gets assigned and echoed with each <div>. Here's the code...Thank you for any comments.
PHP:
for ($i2=0; $i2<$rowscheck; $i2++) {
//FRIEND QUERY COMMENTS
$fr_com = mysqli_query($connect,"SELECT * FROM comments WHERE name_main_id = '".$fcom[$i2]."' ORDER BY comm_id ASC ");
while ($rows_com = mysqli_fetch_array($fr_com)) {
extract($rows_com);
$fcomm[] = $rows_com['comment_main'];
}
}
if ($fr_check > 0 ) {
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "
<div id='frslide'>
<a href='javascript:window_usr($fr_ids)'>
<img src='".$added_fr."' height='68' width='66' hspace='2' vspace='16' id='fadd'/>
</a>
<span style='font-size:12px;position:relative;left:-71px;top:-1px;color:#ffffff; background-image:url(images/back_bar.png);'> ".$frnames2." </span>
</div>
<div id='frdiv' class='frdiv'>
<span style='font-size:12px;position:relative; left:-1px;top:72px;color:#ffffff;background-image:url(images/usr_main.png);'>
<a href='javascript:remusr($fr_ids)'>remove</a>
</span>
</div>
<div>".$fcomm;
}
}
$fcomm variable holds strings of comments from SQL. So when I add $fcomm[$i] or any loop variable to $fcomm it yields just single letters from comments - all I need is to make $fcomm print whole strings but different ones and the ones that correspond to proper each <div>. When I tried to place $fcomm in an inside loop - it prints strings but each string is the same...

You need to increase the index you're trying to retrieve from the fcomm array. Note the changes using $j variable.
if ($fr_check > 0 ) {
$j=0;
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "
<div id='frslide'>
<a href='javascript:window_usr($fr_ids)'>
<img src='".$added_fr."' height='68' width='66' hspace='2' vspace='16' id='fadd'/>
</a>
<span style='font-size:12px;position:relative;left:-71px;top:-1px;color:#ffffff; background-image:url(images/back_bar.png);'> ".$frnames2." </span>
</div>
<div id='frdiv' class='frdiv'>
<span style='font-size:12px;position:relative; left:-1px;top:72px;color:#ffffff;background-image:url(images/usr_main.png);'>
<a href='javascript:remusr($fr_ids)'>remove</a>
</span>
</div>
<div>".$fcomm[$j];
$j++;
}
}

Without knowing your code or column names etc., you probably need to populate $fcomm based on the friend IDs, and then echo out the corresponding comment in the foreach loop.
Something like this:
for ($i2=0; $i2<$rowscheck; $i2++) {
//FRIEND QUERY COMMENTS
$fr_com = mysqli_query($connect,"SELECT * FROM comments WHERE name_main_id =
'".$fcom[$i2]."' ORDER BY comm_id ASC ");
while ($rows_com = mysqli_fetch_array($fr_com)) {
extract($rows_com);
// populate $fcomm sub-array using the ID used to select
// them, i.e. $fcom[$i2]
$fcomm[ $fcom[$i2] ][] = $rows_com['comment_main'];
}
}
if ($fr_check > 0 ) {
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "<div id='frslide'>...</div>";
// echo out the right $fcomm depending on the ID, $fr_ids
foreach ($fcomm[$fr_ids] as $comment) {
echo '<div>', $comment, '</div>';
}
}
}

Related

Get two results while looping trough associative array in PHP

I want to get two results at a time when using while looping trough a associative array in PHP.
I need to echo two results per row, something like this:
<?
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
echo('
<div class="row">
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
<div>
<p>'.$client_name.'</p>
<p >'.$review.'</p>
</div>
</div>
');
}
}
?>
Right now it's giving me the same result twice rather than the next one.
You can use a counter to control the output of the outside div so that you get two inside div output for each outside one:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$client_name = $row['client_name'];
$review = $row['review'];
if ($i % 2 == 0) echo '<div class="row">';
echo '<div><p>'.$client_name.'</p><p>'.$review.'</p></div>';
if ($i % 2 == 1) echo '</div>';
$i++;
}

Display row in database with same data in particular div

Lets say I have data in my database with some rows having the same data.
id|value|message
1|001. |one
2|001. |five
3|002. |four
4|001. |hello
5|001. |sup
6|002. |sure?
Is it possible i echo all message data with 001 together in one <div class="display"></div> and those with 002 with the same <div class="display></div> There by having two <div class="display"></div> display the count of the two different values.
I have tried with PHP using
$sql =<<<EOF
SELECT value, COUNT(value) AS NumOccurrences FROM table WHERE id != '$log_id' GROUP BY value, message ORDER BY id DESC;
EOF;
$ret = $db->query($sql);
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$value = $row['value'];
echo "<div class='display'>$value</div>";
}
But the above code echo six <div class="display"></div>. That is each div for each value
<div class="display">001</div>
<div class="display">001</div>
<div class="display">002</div>
<div class="display">001</div>
<div class="display">001</div>
<div class="display">002</div>
But i want something like this
<div class="display">001001001001</div>
<div class="display">002002</div>
Please I am new to PHP and searched hard for an answer. Is this possible?
Without changing query you can do something like that:
$by_val = array();
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$value = $row['value'];
if(!isSet($by_val[$value])) $by_val[$value] = '';
$by_val[$value] .= $value;
}
foreach($by_val as $key => $str) {
echo "<div class='display'>".$str."</div>";
}

recursive php category tree extended

I have been searching all over the forum but could not locate the answer to my specific question. I hope you can help me, for it has taken me A LOT of time to figure this out as a beginning PHP programmer.
I have a page that listens to this URL : .../.../edit_cat.php?id=24
I want to have a nice category tree. I have accomplished this, but I want all categories with no children to be a link to page post.php and all parent that do have children to be a link but only to show the other categories. Some sort of dropdown menu you might call it. So no children is post.php and if has children then drop the rest of children down. I hope this makes it clear...This is whay I have so far. It works as a tree but not how I wish it to be:
<h2>This is the current category tree</h2>
<?php
category_tree(0);
function category_tree($catid){
include '../config/connect.php';
$result = $db->prepare("SELECT * FROM categories WHERE parent_id = '".$catid."'");
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)):
$i = 0;
if ($i == 0){ echo '<ul class="cattree">';}
echo '<li>' . $row['cat_title'] . '';
category_tree($row['cat_id']);
echo '</li>';
$i++;
if ($i > 0){ echo '</ul>'; }
endwhile;
}
?>
My table of categories looks like this:
cat_id | cat_title | parent_id
1 some_title 0
2 some_title 1
3 title! 2
4 main_title 0
5 titellos! 4
Here is something I did last year, a query returns each line, with the idx, parent_idx and label of the line.
First call:
print_list(1, 0, $lines);
Function:
function print_list($parent, $level, $ar) {
$children = filter_by_parent($parent, $ar);
if (empty($children)) {
return;
}
echo '<ul>';
foreach ($children as $child) {
include PATH_PUBLIC . 'clients/simili/line.php';
print_list($child['Child_Idx'], ($level + 1), $ar);
echo '</li>';
}
echo '</ul>';
}
Second function:
function filter_by_parent($parent_id, $ar){
$retval = array();
foreach($ar as $a) {
if ($a['Parent_Idx'] == $parent_id) {
$retval[] = $a;
}
}
return $retval;
}
And the html called in the function:
<li class="no" data-id="<?php echo $child['Child_Idx']; ?>" data-parent-id="<?php echo $child['Parent_Idx']; ?>">
<i class="fa fa-plus-square-o"></i>
<i class="fa fa-minus-square-o"></i>
<span class="name">
<label><?php echo $child['Child_Name']; ?></label>
<i class="fa fa-book" title="Détails de l'Unité d'Organisation"></i>
</span>
<div class="chiffres">
<span class="inscrits"><?php echo $child['Nb_Collab']; ?></span>
<span class="etp-collab"><?php echo $child['ETP_Collab']; ?></span>
<span class="etp-postes"><?php echo $child['ETP_Postes']; ?></span>
<span class="etp-unit"><?php echo $child['ETP_Unit']; ?></span>
</div>
Ok, I don't know anything about PHP, but here's how you can add a "HasChildren" column to your sql query:
SELECT c.*,
CASE
WHEN EXISTS(SELECT * FROM Categories c1 WHERE c1.parent_id=c.cat_id) THEN 1
ELSE 0
END AS HasChildren
FROM Categories c
WHERE ParentID = #CatID

MySQL Query pagination with PHP

How can i add a pagination system to this simple item display? And how i can add pagination for the results from filter? I just get lost that part and i cant figure it out!
I want to apply CSS on the menu too!
Here's the code:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$result = mysql_query("SELECT * FROM products");
}
while($row=mysql_fetch_assoc($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
?>
EDITED:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$start=0;
$limit=6;
if(isset($_GET['id']))
{
$id = $_GET['id'];
$start = ($id-1)*$limit;
}
$result = mysql_query("SELECT * FROM products LIMIT $start, $limit");
}
while($row = mysql_fetch_array($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
echo "</ul>";
$rows = mysql_num_rows(mysql_query("SELECT * FROM products"));
$total = ceil($rows/$limit);
if($id>1)
{
echo "<center><a href='?id=".($id-1)."' class='button'>Anterior</a></center>";
}
if($id!=$total)
{
echo "<center><a href='?id=".($id+1)."' class='button'>Próximo</a></center>";
}
?>
You should have something like this:
// declare a base query
$q = "SELECT * FROM products";
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
// append filter to query
$q += "where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
// check for "page" URL parameter, if not available, go to first page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// check for "pageSize" URL parameter, if not available, fall back to 20
$pageSize = isset($_GET['pageSize']) ? $_GET['pageSize'] : 20;
// append the pagination to your query
$q += sprintf("LIMIT %d,%d;", ($page-1)*$pageSize, $pageSize);
// execute the constructed query
$result = mysql_query($q);
Note that the code is "pseudoish", not tested, but should give you the base idea.
Also, you can check this SO post about pagination with MySQL.
UPDATE
In PHP if you use an uninitialized variable, then it will have a context-dependent default value. See the documentation about this here. Here is an extract:
It is not necessary to initialize variables in PHP however it is a
very good practice. Uninitialized variables have a default value of
their type depending on the context in which they are used - booleans
default to FALSE, integers and floats default to zero, strings (e.g.
used in echo) are set as an empty string and arrays become to an empty
array.

Assigning new array from existing array php only shows last value of array

I have a slight problem here. I have the following code that I create a search query, and im trying to take "$row" array and create a new array called "$item" so I can echo the values inside my div statement. This code works, and I do echo the $item array with the 'follower_username' values, however only the last value gets echoed out. I have values inside my database Nathan, Brett, Nathan2 and it only echoes Nathan2, or the last value of the array $item.
Here is my code:
$result = mysqli_query($con,"SELECT * FROM followers
WHERE username='$username'");
?>
<?php
while ($row = mysqli_fetch_array($result))
{
$item = $row;
}
?>
<body>
<div id="contentwrap">
<div rel="scrollcontent2">
<?php echo $item['follower_username'];?> <img style="width: 50px; height: auto;"<?php echo '<img src="/user_photo/' . $item['follower_username'] . '.jpeg" />';?>
</div>
I hope I can get this resolved, it is bugging me! Thank you for any help!!
What you're doing is reassigning the value of item to the current row each time.
$row will be an object of table row values from the resulting query so if you want all the rows in an $item variable that would need to be an array to store each result, instead of storing the current row in the same variable for each row.
You will then need to iterate that array to display each result.
$i = 0;
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[$i] = $row;
$i++;
}
<div>
<?php
foreach ($item as $value)
{
echo $value['follower_username'];
}
?>
</div>
Below is an example to show some shorthand versions of the same idea:
$item = array();
while ($row = mysqli_fetch_array($result))
{
$item[] = $row;
}
<div>
<ul>
<?php foreach ($item as $value): ?>
<li><?php echo $value['follower_username']; ?></li>
<?php endforeach; ?>
</ul>
</div>
while ($row = mysqli_fetch_array($result))
What that does is grab the next row in the result set, and assign it to the variable $row. Each time the loop runs, it assigns the latest row to $item. So to store the whole result set, use
$item[] = $row.
I'm sure what you are trying to accomplish with our next line of code. To show all items you need something like
foreach($item as $singleItem)
{
echo $singleItem['follower_username']."<br>";
}

Categories