Iterating values fetched from mysqli - php

So I am creating a dynamic menu. Where I have stored the main categories of the menu in a separate table and subcategories in another table.
They are stored in this way
Categories Table
id cat_name
1 HOME,
2 PRODUCTS,
3 SOLUTIONS,
4 NEWS & GALLERY,
5 DOWNLOADS,
6 CONTACT
Right Now I am running a query
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($query)) {
$row['cat_name'];
$cat=explode(",",$row['cat_name']);
}
Then wherever needed I am printing the values like this
<?php echo $cat[0]; .. echo $cat[1]; //and so on ?>
It looks like this right now. And it is supposed to look likethis
But the problem with this solution is that I have to define the index of the array to print it.
I am developing the admin panel for this one and I want that if the admin adds a new menu item then it should automatically fetch it and display it.
But with this solution it is not possible.
I am thinking of iterating the values with a for loop but cannot get it right.

Use foreach ($query as $rows)
or
Use for ($i=0; $i < count($query); $i++)

Probably You can try this also
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($query))
{
$row['cat_name'];
$cat=explode(",",$row['cat_name']);
foreach($cat as $catss)
{
$cat = trim($catss);
$categories .= "<category>" . $cat . "</category>\n";
}
}

You can try this way may be you wish like this for dynamic menu:
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$menu = '';
$menu .= '<ul>';
while($row = mysqli_fetch_assoc($query))
{
$menu .= '<li>' . $row['cat_name'] . '</li>';
}
$menu .= '</ul>';
echo $menu;
When you are fetching data from table then you can directly print that value using field name. if you want to further use that so, you have to add in one array like:
$cat[] = $row['cat_name'];
then you can use this value in that manner using for or while:
foreach ($cat as $value) {
echo $value;
}

echo '<ul>';
foreach ($cat as $val) {
echo "<li>{$val}</li>";
}
echo '</ul>';
Instead of the index. Also this should be faster and readable than for loop.

You can save it in array then later access the values.
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$cat = array();
while($row = mysqli_fetch_assoc($query)) {
$cat[]=$row['cat_name']
}
Now:
foreach ($cat as $category) {
$cate_gory = explode("," , $category);
foreach ($cate_gory as $categories) {
echo $categories . "<br>";
}
}

Foreach Loop
foreach($cats as $cat)
{
echo $cat;
}
Basic For Loop
for ($i=0; $i<count($cats); $i++)
{
echo $cats[$i];
}
Simple Use Case
<?php
$cats = 'Stack overflow PHP questions';
$cats = explode(' ',$cats);
$html = '<ul>';
foreach($cats as $cat)
{
$html .= '<li>' . $cat . '</li>';
}
$html .= '</ul>';
echo $html;
?>
Your Code
In this case the while loop you are using will iterate over all the values returned from the sql statement, so there is no need to add more complexity. I would remove the commas from the field names and echo out the html this way.
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$html = '<ul>';
while($row = mysqli_fetch_assoc($query)) {
$html .= '<li>' . $row['cat_name'] . '</li>';
}
$html .= '</ul>';
echo $html;
?>

Related

print variable above of the while loop (scope) php

is there is any way to define a variable under the while loop and print it above the while loop
something like this
print $catName
while ($b = mysqli_fetch_assoc($results)) {
$catName = $b['cat'];
}
EDIT
$getBooks = $db->prepare('SELECT
id, cat, instituteId, title, cover, authorName FROM books_library WHERE instituteId=? AND cat=?');
$getList = array();
$getBooks->bind_param('ii', $inId, $cid);
if ($getBooks->execute()) {
$libResults = $getBooks->get_result();
$getList[] = $libResults;
?>
HTML CODE COME HERE
<h3 class="marginBottom8px margin-top_30px text-bold text-danger"><?php echo catName ?></h3>
AND THEN THE WHILE LOOP
while ($book = mysqli_fetch_assoc($libResults)) {
$bokId = $book['id'];
$bookTitle = $bokId['title'];
$catName = $bokId['cat'];
$catName = $bokId['cat'];
now under the while loop I got the $catName How can I echo it above in the <h3></h3>
After the while block, put your h3 html in a variable and print it.
$myHtml = '<h3 class="marginBottom8px margin-top_30px text-bold text-danger">'
. $catName . '</h3>';
print $myHtml;
Don't mix html and php like that.
I think this is what you're after based on the edited question
while ($book = mysqli_fetch_assoc($libResults)) {
echo '<h3>' . $book['cat'] . '</h3>';
}

No data shown when using correct query

I got a small for each loop that I want to test. But it only shows me two empty list items. I also tested the SQL in phpmyadmin and it returns a correct table. I want to show the title from that table but like I said, I am getting two empty list items.
Does anybody know what I am doing wrong?
<?
// content
$content = "SELECT * FROM `snm_content` WHERE catid = 13";
$contentcon = $conn->query($content);
$contentcr = array();
while ($contentcr[] = $contentcon->fetch_array());
foreach($contentcr as $content)
{
$contentje .= '<li>'.$contentcr['title'].'</li>';
}
echo $contentje;
?>
Replace $contentcr by $content inside the foreach loop.
<?
// content
$content = "SELECT * FROM `snm_content` WHERE catid = 13";
$contentcon = $conn->query($content);
$contentcr = array();
while ($contentcr[] = $contentcon->fetch_array());
foreach($contentcr as $content)
{
$contentje .= '<li>'.$content['title'].'</li>'; // Here
}
echo $contentje;
?>
Try this:
while ($contentcr = $contentcon->fetch_array()) {
$contentje .= '<li>'.$contentcr['title'].'</li>';
}
echo $contentje;
Remove foreach use only while
while ($contentcr = $contentcon->fetch_array());{
$contentje .= '<li>'.$contentcr['title'].'</li>';
}

How to avoid repetition of one of several items in array (category name)

I know there are similar questions here and I have read some of the posts and answers, experimented with some of them, but whether it is my limited knowledge of PHP or the peculiarity of my case, I need to ask this.
I am building a dictionary (id, english, bulgarian, theme_id) and would like to group the search results according to theme_id. I am using ORDER BY theme_id, id in my query but I end up displaying the theme with each of the results, while I would like to categorize them as follows:
THEME 1
- result 1
- result 2
THEME 2
- result 3
- result 4
.....
Here is the relevant part of my code:
while($row = mysql_fetch_array($result)) {
//$id = $row['id'];
$english = $row['english'];
$bulgarian = $row['bulgarian'];
$theme_id = $row['theme_id'];
$theme_name = "theme_".$lang;
$theme_query= mysql_query("SELECT theme_id,".$theme_name." FROM ".DICTIONARY_THEMES." WHERE theme_id = ".$theme_id."");
$theme_row = mysql_fetch_array($theme_query);
$theme = $theme_row[$theme_name];
if($source == "english") {
foreach($keywords as $keyword) {
$english = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223\">".$keyword."</span>", $english);
}
$print .= "<li class=\"results-row\">".$theme.": ".$english." = ".$bulgarian."</li>";
}
elseif($source == "bulgarian") {
foreach($keywords as $keyword) {
$bulgarian = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223;\">".$keyword."</span>", $bulgarian);
}
$print .= "<li class=\"results-row\">".$theme.": ".$bulgarian." = ".$english."</li>";
}
}//end while
EDIT: SOLVED, a friend has helped improve my code.
while($row = mysql_fetch_array($result)) {
$english = $row['english'];
$bulgarian = $row['bulgarian'];
$theme_id = $row['theme_id'];
$theme_name = "theme_".$lang;
$theme_query= mysql_query("SELECT theme_id,".$theme_name." FROM ".DICTIONARY_THEMES." WHERE theme_id = ".$theme_id."");
$theme_row = mysql_fetch_array($theme_query);
$theme = $theme_row[$theme_name];
// add all results to an array
$results[] = array(
'english' => $english,
'bulgarian' => $bulgarian,
'theme' => $theme
);
}//end while
$theme = null;
foreach ($results as $result) {
if ($theme != $result['theme']) {
$theme = $result['theme'];
$print .= "<h3>" . $result['theme'] . "</h3>";
}
if ($source == "english") {
foreach ($keywords as $keyword) {
$result['english'] = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223\">" . $keyword . "</span>", $result['english']);
}
$print .= "<li class=\"results-row\">" . $result['english'] . " = " . $result['bulgarian'] . "</li>";
} elseif ($source == "bulgarian") {
foreach ($keywords as $keyword) {
$result['bulgarian'] = preg_replace("|($keyword)|Ui", "<span style=\"color:#780223;\">" . $keyword . "</span>", $result['bulgarian']);
}
$print .= "<li class=\"results-row\">" . $result['bulgarian'] . " = " . $result['english'] . "</li>";
}
}
Based on your code, you should first add all items to an array and afterwards print that array in a separate function/block.
Right after your second MySQL query, put something like
$output[$theme_id] = mysql_fetch_array( $theme_query );
and move all the following code out of the outer result-while-loop (while($row = mysql_fetch_array($result))).
But in fact I would try to put a MySQL query together, to have an ordered, grouped result with all the selected themes in all languages and without querying the database inside a loop.
Or you use something existing, for example this singleton Lexicon class.

How Can i use $_get with build_categories_options function

Now I have create categories and create post is successful but when I edit my post I have problem if edit my post I will lose my category .. I need to get my category in table and I can change it
<?php
$sql = "SELECT catid, catname, parentid FROM categories";
$res = mysql_query($sql);
// initialize $categories to make sure it is an array
$categories = array();
while ($row = mysql_fetch_assoc($res)) {
$parent = intval($row['parentid']);
$categories[$parent][] = $row;
}
?>
<table border="0" cellpadding="10" cellspacing="0">
<tr>
<td valign="top">
<?php
$category_string = "";
function build_categories_options($parent, $categories, $level) {
global $category_string;
if (isset($categories[$parent]) && count($categories[$parent])) {
$level .= " - ";
foreach ($categories[$parent] as $category) {
$opt_value = substr($level.$category['catname'],3);
$category_string .= '<option value=""></option><option value="'.$category['catid'].'">'.$opt_value.'</option>';
build_categories_options($category['catid'], $categories, $level);
}
$level = substr($level, -3);
}
return $category_string;
}
$category_options = build_categories_options(0, $categories, '');
$category_options = '<select class="chosen" name="categories" id="categories">'.$category_options.'</select>';
echo $category_options;
?>
</td>
My problem located in line 25
$category_string .= '<option value=""></option><option value="'.$category['catid'].'">'.$opt_value.'</option>';
I need to get my category in first and show the rest of the results.
For each category, you are displaying two options, an empty option and one with the category information:
$category_string .= '<option value=""></option><option value="'.$category['catid'].'">'.$opt_value.'</option>';
This is inside your loop. So every time your loop iterates, two options will be created. A blank one and one with your category. I'm betting you just need one blank option at the very beginning of the <select>. I think this is what you wanted:
// notice we are initializing $category_string with an empty option here
$category_string = '<option value=""></option>';
function build_categories_options($parent, $categories, $level) {
global $category_string;
if (isset($categories[$parent]) && count($categories[$parent])) {
$level .= " - ";
foreach ($categories[$parent] as $category) {
$opt_value = substr($level.$category['catname'],3);
// removed extra empty category and put it in $category_string initialization
$category_string .= '<option value="'.$category['catid'].'">'.$opt_value.'</option>';
build_categories_options($category['catid'], $categories, $level);
}
$level = substr($level, -3);
}
return $category_string;
}
Also, as #MoeTsao mentioned in the comments, try to avoid using mysql_* functions, as their use is discouraged by PHP. Instead, use mysqli_* or PDO.

PHP - Query and function and while clause?

Question: How can I tie together my query with my function? I would like to print my list, but I am not sure how to connect the two. Also, am I using "entries" correctly below?
/* data handling */
$result = mysql_query("SELECT * FROM Items LEFT JOIN Categories on Categories.CategoryID = Items.FK_CategoryID WHERE Items.FK_UserID = $_SESSION[user_id] ORDER BY CategorySort, CategoryName ASC, ItemSort, ItemTitle");
/* output logic */
function render_list($ItemTitle, array $entries)
{
echo '<ul><li>' . $ItemTitle . '<ul>';
foreach($entries as $entry)
{
echo '<li>' . $entry['ItemID'] . '</li>';
}
echo '</ul></li></ul>';
}
render_list();
Do I need to use a while clause?
// loop through topics
while($row = mysql_fetch_array($result)) {
render_list;
}
Yeah, replace your foreach loop with that while loop. Take that "type" (array) out of the function definition though, you don't need to do that in loosely typed php language. Here's a rework of the code you have:
/* output logic */
function render_list($ItemTitle, $entries)
{
echo '<ul><li>' . $ItemTitle . '<ul>';
while($entry = mysql_fetch_array($entries))
{
echo '<li>' . $entry['ItemID'] . '</li>';
}
echo '</ul></li></ul>';
}
$result = mysql_query("SELECT * FROM Items LEFT JOIN Categories on Categories.CategoryID = Items.FK_CategoryID WHERE Items.FK_UserID = $_SESSION[user_id] ORDER BY CategorySort, CategoryName ASC, ItemSort, ItemTitle");
render_list('My Title', $result);

Categories