How can I produce more than one result in sql ? - php

The following is a query from which I have taken the result.But right now only one result is printing. I have more than one result in the database.. what should i do in order to print more than one result in header tag
<?php
$sqlcategories = $ilance->db->query("SELECT q.title_spa FROM " . DB_PREFIX . "categories q LEFT
JOIN " . DB_PREFIX . "profile_categories a ON (q.cid = a.cid)
WHERE a.user_id = '" . $res_vendor['user_id'] . "'");
if ($ilance->db->num_rows($sqlcategories) > 0)
{
while ($rows = $ilance->db->fetch_array($sqlcategories))
{
$categories='<h3>'.$rows['title_spa'].'</h3>';
}
}
?>

You probably want to change this line:
$categories = '<h3>'.$rows['title_spa'].'</h3>';
to for example:
$categories .= '<h3>'.$rows['title_spa'].'</h3>';

do like this... append string with .= operator
while ($rows = $ilance->db->fetch_array($sqlcategories))
{
$categories .='<h3>'.$rows['title_spa'].'</h3>';
}
echo $categories;
OR need to store in array then
while ($rows = $ilance->db->fetch_array($sqlcategories))
{
$categories[] ='<h3>'.$rows['title_spa'].'</h3>';
}
printr($categories);
thanks

Before your query write:
$categories = "";
And then in while operator use concatenation (note the dot . before = operator)
$categories .= '<h3>'.$rows['title_spa'].'</h3>';
After that print $categories variable
echo $categories;

$categories='';
while ($rows = $ilance->db->fetch_array($sqlcategories))
{
$categories.='<h3>'.$rows['title_spa'].'</h3>';
}

$categories = '<h3>';
while ($rows = $ilance->db->fetch_array($sqlcategories))
{
$categories .= $rows['title_spa'];
}
$categories .= '</h3>';

Related

Iterating values fetched from mysqli

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;
?>

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.

PHP explode array then loop through values and output to variable

The string I am trying to split is $item['category_names'] which for example contains Hair, Fashion, News
I currently have the following code:
$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories = "<category>" . $cat . "</category>\n";
}
I want the outcome of $categories to be like the following so I can echo it out later somewhere.
<category>Hair</category>\n
<category>Fashion</category>\n
<category>News</category>\n
Not sure if I am going the right way about this?
In your code you are overwritting the $categories variable in each iteration. The correct code would look like:
$categories = '';
$cats = explode(",", $item['category_names']);
foreach($cats as $cat) {
$cat = trim($cat);
$categories .= "<category>" . $cat . "</category>\n";
}
update: as #Nanne suggested, explode only on ','
Without a for loop
$item['category_names'] = "Hair, Fashion, News";
$categories = "<category>".
implode("</category>\n<category>",
array_map('trim', explode(",", $item['category_names']))) .
"</category>\n";
echo $categories;
PHP explode array by loop
demo: http://sandbox.onlinephpfunctions.com/code/086402c33678fe20c4fbae6f2f5c18e77cb3fbc2
its works for me
<?php
$str = "name:john,hone:12345,ebsite:www.23.com";
$array=explode(",",$str);
if(count($array)!=0)
{
foreach($array as $value)
{
$data=explode(":",$value);
echo $data[0]."=".$data[1];
echo ' ';
}
}
?>
if you use this:
$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories = "<category>" . $cat . "</category>\n";
}
the $categories string is overwritten each time, so "hair" and "fasion" are lost..
if you however add a dot before the equal sign in the for loop, like so:
$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories .= "<category>" . $cat . "</category>\n";
}
the $catergories string will consist of all three values :)
The error in your code is this:
$categories = "<category>" . $cat . "</category>\n";
You are overwriting $categories at each iteration, it should be:
$categories .= "<category>" . $cat . "</category>\n";
Not sure if I am going the right way about this?
find and replace isn't what explode is for. If you just want to correct the code error - see above.
This is more efficient:
$categories = "<category>" .
str_replace(', ', "</category>\n<category>", $input) .
"</category>\n";
And this also accounts for variable whitespace:
$categories = "<category>" .
preg_replace('#\s*,\s*#', "</category>\n<category>", $input) .
"</category>\n";

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