I've a problem that confuses me and can not get solved...
I have 1 for each loop which runs through all products and then inside I have another for each loop for some specific product parameters that I need to combine into one string (string, array or serialized data) and save info in data base.
foreach ($products as $product) {
$parameter1 = $product_parameter1;
foreach ($products_extra_parameters as $product_extra_parameter) {
$parameter2 .= $product_extra_parameter . '|';
}
$insert_data = "INSERT INTO table (parameter1,parameter2) values ('$parameter1','$parameter1')";
if (!mysqli_query($conn, $insert_data)):
fwrite($fh, "Error: " . $insert_data . "\n" . mysqli_error($conn). "\n");
endif;
}
The problem is that with '.=' it adds previous results to the next product (first product have: 'product1_parameter2_value1|product1_parameter2_value' and next one: 'product1_parameter2_value1|product1_parameter2_value|'product2_parameter2_value1|product2_parameter2_value' and so on and on...
I just need to save combined product attributes in 1 table column (using just string combining or can be serialize) for appropriate product and just this product parameters! And I'll have several such parameters that I need to combine in 1 parameter and save in 1 column...
What I'm missing here/doing wrong?
Related
I have a question regarding php and sql. In the database I have a shop table 'x' in which there is a tags column containing mixed tags from which to filter the collection for the product using the operator 'like'. I have to compare the filtered collection with the collections in column 1 of the store '. If these two collections are equal, then from the store's table in column 2 I can retrieve the appropriate value and enter it into the csv file.
In php I have downloaded the column with tags from the 'x' store, but I have no idea how to add to the category that I searched for by query and compare it with the data from the store 's' column. I tried to explode the resulting strings from the foreach loop with explode () to get an array from each cell in the column, but got the primitive array that was fetched from the database. I also tried a regular for loop but it also failed.
How can you get this one value from the tags column and compare it with the data from another column ?
public static function findEmpikCategory()
{
$empik_lilante_categories = MysqlProvider::getEmpikCategory(); // empik and lilante categories from empik_categories in which the 'collection' is included
// get a specific category (lilante_category) from empik_categories
foreach($empik_lilante_categories as $categories)
{
$lilante_category_from_empik[] = $categories['lilante_category'];
}
return $lilante_category_from_empik;
}
//$lilante_category = explode(",", $lilante_category_for_offers_products, 0);
// searching lilante categories from the shopifyProductsLilante array
public static function findLilanteCategory()
{
$empik_cateries_equals_lilante_categories = MysqlProvider::getEmpikCategoryEqualLilanteCategory(); // empik categories corresponding to lilante categories
$lilante_category_to_check = CSVFileGenerator::findEmpikCategory();
$lilante_category_for_offers_products = MysqlProvider::getLilanteCategoryByOffersEmpik(); // lilante categories for all empik products
//print_r($lilante_category_to_check);
foreach($lilante_category_for_offers_products as $lilanteCategories)
{
foreach($lilanteCategories as $lilanteCategory)
{
echo "<br/>";
//print_r($lilanteCategory);
echo "<br/>";
print_r(explode(",", $lilanteCategory, 0));
//echo "<br/>";
// echo gettype($lilanteCategory) . "<br>"; // each element is a string
// print_r($lilanteCategory);
}
}
foreach($lilante_category_to_check as $lilanteCategoryFromEmpik)
{
echo "<br/>";
print_r($lilanteCategoryFromEmpik);
echo "<br/>";
}
//fclose($file_open);
return ;
}
I have small issue with a for() loop that displays values inside another foreach() loop in a dynamic way.
A small background of the code:
The output table is created dynamically based on the values obtain from one mysql query SELECT (which is the 1st select) from 1 column (that has name "coloane") in a table called "categories";
The values stored in the column "coloane" are actually the name of some columns from another table called "articles"
The first mysql select is to obtain the values from the column "coloane" so I can create the second.
After the second table returns rows (num_rows() > 0) I start to create the table.
The table has 2 static columns that are always present, and the rest of the columns are added dynamically based on different criteria.
The plot:
I explode the values obtained from the first select - from the column "coloane" - to make the [th]'s for the table header;
this explode I store it under the variable "$rows_th";
to make the [th]'s for the table header, i use a foreach() loop (and here I also remove any underscores);
after that I proceed to create the [tbody] and the [td]'s using another foreach(), only that this foreach is done for the values of the second select;
inside this foreach() I create another loop, using the for() function on the variable "$rows_th" so the table has the same length;
here the values are combined like this:
'<td id="'.$i.'">'.$values_td[$rows_th[$i]].'</td>';
The main issue is that, using the format listed above, it will only display the first value!
When I tried to verify the "$values_td[$rows_th[$i]]" using the is_string() function, I discovered that the first value is a string, and after that, every other value is not a string...
The test performed:
if (is_string($values_td[$rows_th[$i]]))
print '<td id="'.$i.'">Value found!!!</td>';
} else {
print '<td id="'.$i.'">No luck...</td>';
}
Any ideas on what might be going wrong ?
I know I'm missing something, but I just can't seem to figure it out :-/
The entire code is listed here: http://pastebin.com/4MFifh92
In the mean time, with the help from a friend, I finally found what was going wrong.
The variable turns from string to number because in the table called "categories", the column named "coloane" has the values inside devided by a "," (comma) and a " " (space), like so
------------------------------------------
| coloane |
------------------------------------------
make, model, location, comments, status
------------------------------------------
To fix this, I found out that I can try to do a str_replace in a simple foreach() loop :)
Something like this:
$i=0;
foreach($rows_th as $values_th) {
$i++;
$cols_td = str_replace(' ', '', $values_th);
$actual_value = $values_td->$cols_td;
print '<td id="'.$i.'">'.$actual_value.'</td>';
}
And this did the trick :)
Hope this will help others that came across with issues similar to this :)
Best regards,
Mike
Can't you just do something like:
SELECT * FROM results_query_header_by_cat WHERE `id` = 3;
Then:
SELECT * FROM results_query_content_by_cat WHERE `id_category` = 3;
Then with the results:
echo '[thead]';
foreach ( $results as $result ){
foreach( $result['coloane'] as $header ){
echo '[th]'.$header.'[/th]';
}
}
echo '[/thead][tbody]';
foreach ( $records as $record ){
echo '[tr][td]' .
$result['producator'] . '[/td][td]' .
$result['model'] . '[/td][td]' .
$result['imei'] . '[/td][td]' .
$result['locatie'] . '[/td][/tr]';
}
echo '[/tbody]';
Is that what you're looking for?
e: I haven't tried this but I'd imagine it's something like that. Just:
get the headers by category ID
get the records by category ID.
Echo the first result set as headers with a loop,
echo the second result set as table rows with columns in a loop.
if(count($search)==0) {
for($i=0;$i<count($about);$i++) {
$bd->insert("search","page_title,page_description,page_url,image_id","'About','{$about[$i]['image_title']}','http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."','{$about[$i]['uniq_id']}'");
}
} else {
for($i=0;$i<count($about);$i++) {
for($k=0,$j=0;$k<=$i,$j<count($search);$j++,$k++) {
if($search[$j]['image_id']==$about[$i]['uniq_id']) {
echo "update".$i.'and'.$k.'and'.$j;
echo"<br>";
$bd->update("search",
"page_title='About',page_description='{$about[$i]['image_title']}',page_url='http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."' ","image_id='{$about[$i]['uniq_id']}' limit 1");
}
}
}
}
$search is an array which I am getting from my database . first I m checking if the search table is empty or not . if empty then insert the values in the search table .
$about is also an array which i am getting from my database . if $search is not empty Then I am updating the value but checking first that $search[$j]['image_id']===$about[$i][uniq_id] and HERE IS MY PROBLEM START :
Suppose in my table about there are 3 entries ie :
uniq_id=1
uniq_id=2
uniq_id=3
and In my table search there are 2 entries ie:
image_id=1
image_id=2
So the search table is not empty So it will follow the 2nd condition. So i was trying that table $about[1]['uniq_id'] should check for $search[1]['image_id'] and $search[2]['image_id'] and etc $search[$i]['image_id'] if the table has any values
but I my for loop is not working like I want So anybody can help me in this
You'll need to know which rows in the "search" table need adding (INSERT) and which ones need updating.
Perhaps try looping through the "search" array first and find which "image_id" values you have.
$image_ids = array();
foreach ($search as $item) {
$image_ids[] = $item['image_id'];
}
Next, loop through the "about" array. Use the ID's in the "$image_ids" array to determine whether you need to UPDATE or INSERT an item.
foreach ($about as $item) {
if (in_array($item['image_id'], $image_ids)) {
// Item already exists. Update it.
} else {
// Item doesn't exist. Add it.
}
}
This is also much faster than putting loops inside loops.
Forward:
I've checked through the similarly worded questions on Stack Overflow but none are specific to what I'm attempting.
What I have:
I have session data, two loops and a SQL table.
The first loop checks for specific existing session data and uses
the keys (rather than the values) of this data to determine what ids
should be selected (SQL) from a table.
The second loop outputs the SQL results row by row.
...this can also be described in a less abstract and friendlier manner:
The first loop looks for items currently added to the shopping cart
(key = product id, value = quantity) to determine what products
should be listed on "Your order" page.
The second loop list rows of data associated with each product id
such as the title, description and unit cost.
What I need:
Since my session data consists of products ids (keys) and a corresponding quantity (values) I need to show the quantity as part of each outputted row.
id | title | description | unit cost | amount | subtotal
session data key | from database | from database | from database | session data value | basic PHP math
(also in database) (unit cost * amount)
My code:
The first loop to use the session data keys to query the require products:
$id_from_session = "WHERE id = '9999999999'"; //fix due to not being sure how to simuataneously incorporate "WHERE" and "OR" into query loop (only looping the "OR" condition).
foreach($_SESSION['post'] as $key=>$value)
{
$id_from_session .= "OR id ='".$key."'";
}
The second loop to output the resulting rows of the query:
foreach ( $yourorders as $yourorder )
{
?>
<?php echo $yourorder->title; ?></br>
<?php echo $yourorder->description; ?></br>
<?php echo $yourorder->value; ?></br>
<?php /* I NEED THE QUANTITY HERE */ ?></br>
<?php /* VALUE * QUANTITY HERE */ ?></br>
<?php
}
<?php /* OVERALL TOTAL OUTSIDE OF LOOP */ ?></br>
My question:
How do I incorporate the quantity from the session data loop (and the quantity * unit value) into the SQL results loop?
$_SESSION['post'][$yourorder->id]
should get you the quantity right? so,
<?php echo $_SESSION['post'][$yourorder->id]; ?>
or if short tags are allowed
<?= $_SESSION['post'][$yourorder->id]; ?>
Also a nicer way to build the WHERE string.
$where = array();
foreach($_SESSION['post'] as $key=>$value)
{
$where[] = "id ='".$key."'";
}
$id_from_session = "WHERE " . implode(' OR ', $where);
$_SESSION['post'][$yourorder->id] gives you the quantity since the keys are the product ids :)
well.. if you can be absolutely sure that your shopping cart keys don't need to be escaped you can write this:
$id_from_session = "WHERE id IN ('" . implode( "', '", array_keys($_SESSION['post']) ) . "')";
The goal of this code, is to get all brands for all stores into one array, and output this to the screen. If a brand exists in multiple stores, it will only be added once.
But I feel I have too many for loops, and that it might choke the CPU on heavy traffic.
Is there a better solution to this?
function getBrands($stores, $bl)
{
$html = "";
//Loop through all the stores and get the brands
foreach ($stores as $store)
{
//Get all associated brands for store
$result = $bl->getBrandsByStore($store['id']);
//Add all brands to array $brands[]
while ($row = mysql_fetch_array($result))
{
//If this is the first run, we do not need to check if it already exists in array
if(sizeof($brands) == 0)
{
$brands[] = array("id" => $row['id'], "name" => $row['name']);
}
else
{
// Check tosee if brand has already been added.
if(!isValueInArray($brands, $row['id']))
$brands[] = array("id" => $row['id'], "name" => $row['name']);
}
}
}
//Create the HTML output
foreach($brands as $brand)
{
$url = get_bloginfo('url').'/search?brandID='.$brand['id'].'&brand='.urlSanitize($brand['name']);
$html.= ''.$brand['name'].', ';
}
return $html;
}
//Check to see if an ID already exists in the array
function isValueInArray($values, $val2)
{
foreach($values as $val1)
{
if($val1['id'] == $val2)
return true;
}
return false;
}
From your comment, you mention "Guide table has X stores and each store has Y brands". Presumably there's a "stores" table, a "brands" table, and a "linkage" table, that pairs store_id to brand_id, in a one-store-to-many-brands relationship, right?
If so, a single SQL query could do your task:
SELECT b.`id`, b.`name`
FROM `stores` s
LEFT JOIN `linkage` l
ON l.`store`=s.`id`
LEFT JOIN `brands` b
ON b.`id`=l.`brand`
GROUP BY b.`id`;
That final GROUP BY clause will only show each brand once. If you remove it, you could add in the store ID and output the full list of store-to-brand associations.
No need to loop through two sets of arrays (one to build up the array of brands, and then one to make the HTML). Especially since your helper function does a loop through -- use the array_key_exists function and use the ID as a key. Plus you can use the implode function to join the links with ', ' so you don't have to do it manually (in your existing code you'd have a comma on the end you'd have to trim off). You can do this without two sets of for loops:
function getBrands($stores, $bl)
{
$brands = array();
//Loop through all the stores and get the brands
foreach ($stores as $store)
{
//Get all associated brands for store
$result = $bl->getBrandsByStore($store['id']);
//Add all brands to array $brands[]
while ($row = mysql_fetch_array($result))
{
if (!array_key_exists($row['id'])
{
$url = get_bloginfo('url') . '/searchbrandID=' .
$brand['id'] . '&brand=' . urlSanitize($brand['name']);
$brands[$row['id']] .= '<a href="' . $url . '" id="' .
$brand['id'] . '" target="_self">' .
$brand['name'] . '</a>';
}
}
}
return implode(', ', $html);
}
That will get you the same effect a little faster. It's going to be faster because you used to loop through to get the brands, and then loop through and build up the HTML. Don't need to do that as two separate loops so it all at once and just store the HTML as you go along. Plus since it's switched to use array_key_exists, instead of the helper you wrote that checks by looping through yet again to see if a brand is in there, you'll see more speed improvements. Hashmaps are nice like that because each element in the hashmap has a key and there are native functions to see if a key exists.
You could further optimize things by writing a better SQL statement with a distinct filter to make it so you don't have to do a while inside a foreach.
How are your tables designed? If you had a store table, a brand table, and a link table that had the relationship between stores and brands, you could just pull in the list of brands from the brand table in one query and not have to do any other logic.
Design your tables so they easily answer the questions you need to ask.
If you need to get all the brands for a certain set of stores then you should consider using a query crafted to do that instead of iterating through all the stores and getting the separate pieces of information.