I have 2 tables. First one is categories and the second is items.
I need my script to print to .txt file the name of the category and underneath it category items with matching 'category_id'. My code uses first while loop to iterate through the categories and second to iterate through items. Everything works fine until we get to second while loop, because then values become empty.
while ($row2 = mysqli_fetch_array($query_for_categories)) {
fwrite($fp, $row2["category_name"].PHP_EOL);
while ($row = mysqli_fetch_array($query_for_items)) {
if ($row2['id_category_from_category'] == $row['id_category_from_items']) {
fwrite($fp, $row["item_name"].PHP_EOL);
}
}
}
After the first iteration of the outer while loop, you will have fetched all the rows from $query_for_categories. There will be no more rows to fetch from that query on subsequent iterations of the outer while loop.
You can fetch them all into an array first
while ($row = mysqli_fetch_array($query_for_items)) {
$items[] = $row;
}
Then use the rows from that array instead of a while ... fetch loop.
while ($category = mysqli_fetch_array($query_for_categories)) {
fwrite($fp, $category["category_name"].PHP_EOL);
foreach($items as $item) {
if ($category['id_category_from_category'] == $item['id_category_from_items']) {
fwrite($fp, $item["item_name"].PHP_EOL);
}
}
}
It does seem like you could probably do this with one query using a join, though. I'd recommend checking into that instead of doing it this way. Based on the column names in your code, the query would be something like this:
SELECT c.category_name, i.item_name
FROM categories c
LEFT JOIN items i on c.id_category_from_category = i.id_category_from_items
ORDER BY c.category_name, i.item_name
Then you could print the items with categories in one loop like this:
$previous_category = null;
while ($item = mysqli_fetch_array($query)) {
// each time category changes, output the new category name
if ($item['category_name'] != $previous_category) {
fwrite($fp, $item["category_name"].PHP_EOL);
// then current category becomes previous category
$previous_category = $item['category_name'];
}
fwrite($fp, $item["item_name"].PHP_EOL);
}
I do wonder how you can tell which of the lines in the file are items and which are categories, though. Maybe you should output some kind of indicator for that?
Related
I'm trying to combine two tables from a database, and based on my first one, I want to retrieve some value from the other one, and add them to an array.
Here's my problem:
My first database looks like that:
FIRST TABLE:
id, credit_type, association_name, address, city, province, postal_code, country, cycle_type, cycle_begin, cycle_months
My second database instead looks like that:
SECOND TABLE:
id, association_id, designation_name
The id in my first table matches the association_id in my second table so I don't need an INNER JOIN.
My approach is the following:
<?php
public function my_function()
{
$sql = ee()->db->select('*')->from('first_table')->get();
$data['database'] = [];
if ($sql->num_rows() > 0)
{
foreach($sql->result_array() as $row)
{
$id[] = $row['id'];
$data['database'][] = $row;
}
}
foreach ($data['database'] as $key => $value) {
$association_query = ee()->db->query("SELECT * FROM second_table WHERE id = $id");
foreach($association_query->result_array() as $row_two)
{
if ($association_query->num_rows() > 0)
{
$data['database'][$key]['associations'][] = $row_two['designation_name'];
}
}
}
return ee()->load->view('index', $data, true);
}
?>
The sintax ee()->db->select('*') is a prepared statment from expression engine and it's equal to SELECT * FROM first_table (sanitaized).
So as you can see, I try to pass the value $id, which is an array, to my query. The thing is that as soon as I push the value like that $id[] = $row['id'] I create a nice array, but when I loop through my foreach loop, it multiplies my array in many other arrays so I'm not able to run my query, even if I'm technically in a foreach loop.
Plus, as soon as I try to push the result of my query in my array, let's say changing the id in a static id for instance id=3, I obtain a really weird result, like so many arrays repeated with 1 value, 2 value, 3 value and so on, when I'd like to push my key 'association' only where it is presented in the other table.
If you won't do it on SQL, at least don't execute the second query so many times.
<?php
public function my_function()
{
$assocs = array();
$data = array('database' => array());
$association_query = ee()->db->query("SELECT * FROM second_table");
if ($association_query->num_rows() > 0) {
foreach($association_query->result_array() as $row) {
$assocs[$row['association_id'][] = $row['designation_name'];
}
}
$sql = ee()->db->select('*')->from('first_table')->get();
if ($sql->num_rows() > 0) {
foreach($sql->result_array() as $row) {
$id_check = $row['id'];
if (isset($assocs[$id_check])) {
$row ['associations'] = $assocs[$id_check] ;
}
$data['database'][] = $row;
}
}
return ee()->load->view('index', $data, true);
}
?>
Regards
I have a MySQL database with a table called product. Columns are id, product_name, price, category. I use PDO with fetchAll and sort by category. I would like to create HTML tables for each category grouping. In the past I've always done something like this:
$category = "";
$html = "";
foreach($results as $row){
if ($row['category'] != $category){
if ($category != "")
$html .= "</table>";
$category = $row['category'];
$html .= "<table>";
}
//code for table row here
}
$html .= "</table>";
However, I am wondering if there is a different way to do this such as splitting an array by categories and running a foreach on each sub-array. Is this possible?
Edit:
To explain further, I am looking for something that is not as cumbersome. I prefer not having to check what the previous category was (or if it was empty). I prefer not having to specify a closing </table> tag twice. If an array can be split by category then this would get around these issues by just running a nested loop on each of the categories.
Edit 2:
For some reason this question was listed as opinion based. Can someone inform me as to what is opinion based about my question? I will then try to improve it.
If you wanted to skip the whole category check then yes, you could create a new array.
$productCategories = array();
foreach ($results as $result) {
$productCategories[$result['cat']][] = $result;
}
foreach ($productCategories as $productCategory) {
// Start table
foreach ($productCategory as $product) {
// Render product
}
// End table
}
I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.
Here is my problem. I am returning results from a mysql database and using a for loop to echo the results. Though its getting a little complicated because I am using some table data to nest inside other results. This code returns "Pablo Picasso" inside a div called "Spain", fine, but if there is "El Greco" in Spain too, then I get two "Spain" divs, rather than just the one.
So: I'd like to only return a result once for each unique value in a table column, rather than for every one.
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
foreach ($results as $row)
{
echo "<div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
$tempCountry = $row['country'];
foreach ($results as $row)
{
if ($row['country']== $tempCountry) echo "<div>artists name</div>";
}
echo "</div>";echo "</div>";
}
I'm wondering if it is the construction of the nested loop, or something else, I don't know!!! Please help
I agree with #Kalpesh that you need to order the results by country.
Right now you have multiple nested loops when all you really should need is one. Try using just one loop to go through the data. On every iteration, check the $tempCountry value to see if it different compared to the current row's country. If it is, you need to close the current <div>, open a new <div> and update the $tempCountry value. Otherwise, echo the name of the artist.
EDIT: Psuedocode added below
Retrieve data from database (the query should sort the data by country)
Initialize $tempCountry to null
Loop over every row
If $tempCountry equals this row's country
Print the artist
Else
Set $tempCountry equal to this row's Country
Close the div tag
Open a new div tag
Print the artist
Note that you do not want to close the div tag on the first time through the loop. Also, you need to close the div tag after the loop finishes.
foreach ($results as $row) {
if ($tempCountry == $row['country']) {
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
else {
$tempCountry == $row['country'];
echo "</div><div class=\"".$row['country']."\">".$row['country'];
echo "<div class=\"Box\">";
echo "<div>artist</div></div>";
}
echo "</div>";
}
Create an empty array outside of your loop. On output push the values of $row into the array inside of your loop. Then only output if value does not already exist in the array. You can use in_array for this.
The solution I found was to nest a foreach inside another, the outer loop SELECTS with a GROUP BY.
In this example I get one outer for each country, then inside that , every person (or item) within that country (or with that column value). Really useful.
NEW CODE: SOLUTION (use GROUP BY to build outer container)
// create array to build group div
$country = mysql_query("SELECT * FROM table GROUP BY `country`");
// create array for inner contents
$result = mysql_query("SELECT * FROM table ORDER BY name");
//array for group(countries in this instance)
$countrys = array();
while ($row = mysql_fetch_assoc($country)) {
$countrys[] = $row;
}
//array for inner contents
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}
$tempCountry="";
foreach ($countrys as $row)
{
$tempCountry = $row['country'];
echo "<div class=\"".$row['country']."\">";
echo $row['country'];
echo "<div class=\"Box\">";
foreach ($results as $row) {
if ($tempCountry == $row['country'])
{
echo"<div>inner contents of that group</div>";
}
}
echo "</div>";
echo "</div>";
}
i want to make a website something like popurls.com, but I will use static data stored in MySQL database. Btw I use php/mysql.
In each list i want to show around 10 links (just like on popurls). In that case, if I would have 20 lists, i would need to make 20 'for' loops (for each particular list).
My question is; is there some better way to print that 20 lists instead of using 20 'for' loops in php.
a for loop or a foreach loop will work fine, but it will be a lot less coding if you just create a single for loop and push content into an array of arrays or an array of strings... you can then do whatever you'd like with the actual content (assuming we're grouping by a column category. I'll use an example that uses an array of strings (and the query that I reference is explained here: http://explainextended.com/2009/03/06/advanced-row-sampling/)
$query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error());
$all_items = array();
while($row=mysql_fetch_array($query)){
if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string
$all_items[$row['category']] = "";
}
$all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list
}
Now we have an array where the block of HTML for each section is stored in an array keyed by the name of the category. To output each block, just:
echo $all_items['category name'];
PHP's foreach http://php.net/manual/en/control-structures.foreach.php
Depends a lot on your data input but I could imagine something like this:
<?php
$lists = arrray('list1', 'list2', 'list3');
foreach ($lists as $current) {
$data = fetch_data_from_mysql($current);
foreach ($data as $link) {
echo "Link";
}
}
function fetch_data_from_mysql($current)
{
$list_data = array();
// do whatever is required to fetch the list data for item $current from MySQL
// and store the data in $list_data
return $list_data;
}
You just need two foreach loops. Assuming that you take the data from a mysql table (like you wrote), this could be like this:
$list_query = mysql_query("SELECT * FROM lists";)
while( $list = mysql_fetch_array($list_query) )
{
echo "<h1>{$list['title']}</h1>";
$query = mysql_query("SELECT * FROM entries WHERE list_id = {$list['id']}");
while( $entry = mysql_fetch_array($query) )
{
echo "- {$entry['name']}<br />";
}
}
You can get all the information from the database and parse it into an array, something like
array[<news type1>] = array( link1, link2, link3, etc);
array[<news type2>] = array( link1, link2, link3, etc);
and so on
and on the layout you can use
foreach ($newsCategory AS $categoryLinks) {
foreach ($categoryLinks AS $newsLink) {
<show the link and / or extra data>
}
}
Just store your links in two-dimensional array. That way you'll have to make 1 outer loop (iterating over lists) and 1 inner loop iterating over links in a particular list.
$links = array(
'science' => array('link1', 'link2', ...),
'sports' => array('link1', 'link2'),
// ... and so on
);
foreach ($links as $category => $urls) {
echo "Links in category: $category\n";
foreach ($urls as $url) {
echo $url . "\n";
}
}