How do I combine two statement will be one query? - php

Here an example queries to get two type of icons..
$fetchIcon = array();
$queryIcon = $db->query("SELECT * FROM icon_code WHERE icon_type = 'icon'");
while ($fIcon = $db->fetch_assoc($queryIcon)) {
$fetchIcon[] = $fIcon;
}
$fetchOther = array();
$queryOther = $db->query("SELECT * FROM icon_code WHERE icon_type = 'other'");
while ($fOther = $db->fetch_assoc($queryOther)) {
$fetchOther[] = $fOther;
}
Then I use foreach to show an ouput on the same page.
foreach ($fetchIcon as $Icon) {
echo $Icon['IconName']; // select option for Icon
}
foreach ($fetchOther as $Other) {
echo $Other['IconName']; // select option for other icon
}
Question :
How do I combine the two statement will be one query?

SELECT * FROM icon_code
WHERE icon_type = 'icon'
or icon_type = 'other'
ORDER BY icon_type
or
SELECT * FROM icon_code
WHERE icon_type in ('icon', 'other')
ORDER BY icon_type
The order byis optional to get the order by type.

SELECT *
FROM icon_code
WHERE icon_type IN ('icon', 'other')
and then
$fetchIcon = array();
$fetchOther = array();
while($row = mysql_fetch_assoc($result)) {
switch($row['icon_type']) {
case 'icon':
$fetchIcon[] = $row;
break;
case 'other':
default:
$fetchOther[] = $row;
}
}

I would suggest using the IN function:
$queryOther = $db->query("SELECT * FROM icon_code WHERE icon_type IN ('other', 'icon'");

Related

How to redirect to you tube using PHP

i have a site it running on a platform called "photo store" its a PHP site. there is image i want some one click that image redirect to my you tube channel but problem is all pages loading from template.so i did some coding and add a few line with if statement first i did only echo that works but when i try to redirect to YouTube it wand load 500 error coming can anyone help me??
this is a code
if(strpos($_SERVER['HTTP_REFERER'],'cart.php') or strpos($_SERVER['HTTP_REFERER'],'index.php')) // Clear the crumbs if coming from the cart or index
unset($_SESSION['crumbsSession']);
try
{
//$useGalleryID = $galleryID; // Original untouched gallery ID
$useMediaID = $mediaID; // Original untouched media ID
if(!$mediaID) // Make sure a media ID was passed
$smarty->assign('noAccess',1);
else
{
if($config['EncryptIDs']) // Decrypt IDs
{
$mediaID = k_decrypt($mediaID);
$useGalleryID = k_encrypt($_SESSION['id']);
}
else
$useGalleryID = $_SESSION['id'];
//echo $mediaID;
idCheck($mediaID); // Make sure ID is numeric
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM {$dbinfo[pre]}media WHERE media_id = '{$mediaID}'";
$mediaInfo = new mediaList($sql);
if($mediaInfo->getRows())
{
if($mediaID==985){
echo $mediaID;
window.location.replace("http://www.youtube.com");
}
else{
$media = $mediaInfo->getSingleMediaDetails('preview');
$galleryIDArray = $mediaInfo->getMediaGalleryIDs(); // Get an array of galleries this media is in
if(#!in_array($mediaID,$_SESSION['viewedMedia'])) // See if media has already been viewed
{
$newMediaViews = $media['views']+1;
mysqli_query($db,"UPDATE {$dbinfo[pre]}media SET views='{$newMediaViews}' WHERE media_id = '{$mediaID}'"); // Update views
$media['views'] = $newMediaViews; // Update the array so the count shown is the new count
$_SESSION['viewedMedia'][] = $mediaID;
}
//print_r($media); exit;
/*
if(!$_SESSION['crumbsSession']) // Get a crumb trail - doesn't work for contibutors yet
{
#$galleryInfo = mysqli_fetch_assoc(mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_galleries WHERE gmedia_id = '{$mediaID}' ORDER BY mg_id LIMIT 1"));
if($galleryInfo['gallery_id'])
{
$galleriesMainPageLink['page'] = "gallery.php?mode=gallery";
$_SESSION['galleriesData'][0]['linkto'] = linkto($galleriesMainPageLink); // Check for SEO
$_SESSION['galleriesData'][0]['name'] = $lang['galleries']; //
$_SESSION['crumbsSession'] = galleryCrumbsFull($galleryInfo['gallery_id']);
}
}
*/
// Check for video sample
$mediaInfo2 = new mediaTools($mediaID);
if($media['dsp_type'] == 'video') // Make sure the DSP type is set to video
{
if($video = $mediaInfo2->getVidSampleInfoFromDB()) // Make sure video file exists
{
$videoCheck = $mediaInfo2->verifyVidSampleExists();
if($videoCheck['status']) { // Make sure the video exists
//print_k($videoCheck); exit;
if($videoCheck['url'] and $config['passVideoThroughPHP'] === false)
$video['url'] = $videoCheck['url']; // Use URL method
else
$video['url'] = $config['settings']['site_url'].'/video.php?mediaID='.$media['encryptedID']; // Use PHP pass-through
//echo $video['url']; exit;
//print_k($video);
$media['videoStatus'] = 1;
$media['videoInfo'] = $video;
} else {
$media['videoStatus'] = 0;
}
}
else
$media['videoStatus'] = 0;
}
else
{
/*
* Get an estimated preview width and height
*/
$sample = $mediaInfo2->getSampleInfoFromDB();
$sampleSize = getScaledSizeNoSource($sample['sample_width'],$sample['sample_height'],$config['settings']['preview_size'],$crop=0);
$media['previewWidth'] = $sampleSize[0];
$media['previewHeight'] = $sampleSize[1];
}
$mediaPrice = getMediaPrice($media); // Get the media price based on the license
$mediaCredits = getMediaCredits($media); // Get the media credits based on the license
// Get category ID - Make sure member has access to category - maybe add this later
$galleryIDArrayFlat = ($galleryIDArray) ? implode(",",$galleryIDArray) : 0;
/*
* Prints *****************************************************************************************************************************
*/
$galleryPrintsResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}prints
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}prints.print_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'prints'
AND ({$dbinfo[pre]}prints.attachment = 'media' OR {$dbinfo[pre]}prints.attachment = 'both')
"
); // Find out which prints are assigned to galleries this photo is in
$galleryPrintsRows = mysqli_num_rows($galleryPrintsResult);
while($galleryPrint = mysqli_fetch_array($galleryPrintsResult))
$printIDArray[] = $galleryPrint['item_id'];
$mediaPrintsResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_prints WHERE media_id = '{$mediaID}'"); // Find what prints have been directly assigned to this photo // GROUP BY print_id
$mediaPrintsRows = mysqli_num_rows($mediaPrintsResult);
//echo $mediaPrintsRows; exit; // Testing
while($mediaPrint = mysqli_fetch_array($mediaPrintsResult))
{
if($mediaPrint['printgrp_id']) // Is a group assignment
{
// Select print groups
$mediaPrintsGroupsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}prints
LEFT JOIN {$dbinfo[pre]}groupids
ON {$dbinfo[pre]}prints.print_id = {$dbinfo[pre]}groupids.item_id
WHERE {$dbinfo[pre]}groupids.group_id = '{$mediaPrint[printgrp_id]}'
AND {$dbinfo[pre]}prints.active = 1
AND {$dbinfo[pre]}prints.deleted = 0
AND {$dbinfo[pre]}groupids.mgrarea = 'prints'
"
);
//$pgRows = mysqli_num_rows($mediaPrintsGroupsResult); // Testing
//echo $pgRows;
while($mediaPrintsGroup = mysqli_fetch_array($mediaPrintsGroupsResult))
$printIDArray[] = $mediaPrintsGroup['print_id'];
}
else
{
$printIDArray[] = $mediaPrint['print_id'];
if($mediaPrint['customized'])
{
$printCustomizedIDs[] = $mediaPrint['print_id']; // Add this ID to the custom array list
$customPrint[$mediaPrint['print_id']] = $mediaPrint; // Get the actual values for the custom item
}
}
}
if($printIDArray)
$printsIDArrayFlat = implode(",",$printIDArray);
else
$printsIDArrayFlat = 0;
// Now that we have the print ID array select the prints that the customer has access to and assign them to smarty
$printsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}prints
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}prints.print_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'prints')
WHERE ({$dbinfo[pre]}prints.print_id IN ({$printsIDArrayFlat}) OR {$dbinfo[pre]}prints.all_galleries = 1)
AND {$dbinfo[pre]}prints.active = 1
AND {$dbinfo[pre]}prints.deleted = 0
AND ({$dbinfo[pre]}prints.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
ORDER BY {$dbinfo[pre]}prints.sortorder
"
);
if($returnRows = mysqli_num_rows($printsResult))
{
while($print = mysqli_fetch_assoc($printsResult))
{
$print['price'] = defaultPrice($print['price']); // Make sure to assign a default price if needed
$print['credits'] = defaultCredits($print['credits']); // Make sure to assign default credits if needed
/*
* Custom Pricing calculations
*/
if(#in_array($print['print_id'],$printCustomizedIDs))
{
$print['price_calc'] = $customPrint[$print['print_id']]['price_calc'];
$print['price'] = defaultPrice($customPrint[$print['print_id']]['price']);
$print['credits'] = defaultCredits($customPrint[$print['print_id']]['credits']);
$print['credits_calc'] = $customPrint[$print['print_id']]['credits_calc'];
$print['quantity'] = $customPrint[$print['print_id']]['quantity'];
}
/*
* Advanced Pricing calculations
*/
switch($print['price_calc'])
{
case 'add':
$print['price'] = $mediaPrice + $print['price'];
break;
case 'sub':
$print['price'] = $mediaPrice - $print['price'];
break;
case 'mult':
$print['price'] = $mediaPrice * $print['price'];
break;
}
switch($print['credits_calc'])
{
case 'add':
$print['credits'] = $mediaCredits + $print['credits'];
break;
case 'sub':
$print['credits'] = $mediaCredits - $print['credits'];
break;
case 'mult':
$print['credits'] = $mediaCredits * $print['credits'];
break;
}
//echo $mediaCredits.'-'.$print['credits'].'-'.$print['credits_calc']."/";
if($print['quantity'] != '0') // Make sure the quantity is other than 0
{
$printsArray[$print['print_id']] = printsList($print,$mediaID);
$optionsResult = mysqli_query($db,"SELECT og_id FROM {$dbinfo[pre]}option_grp WHERE parent_type = 'prints' AND parent_id = '{$print[print_id]}' AND deleted = 0"); // See if there are any options for this item
if(mysqli_num_rows($optionsResult))
{
$printsArray[$print['print_id']]['addToCartLink'] = $printsArray[$print['print_id']]['linkto']; // Workbox popup
$printsArray[$print['print_id']]['directToCart'] = false; // Workbox popup
}
else
{
if($config['EncryptIDs'])
$printsArray[$print['print_id']]['addToCartLink'] = "{$siteURL}/cart.php?mode=add&type=print&id=".$printsArray[$print['print_id']]['encryptedID']."&mediaID={$media[encryptedID]}"; // Direct to cart
else
$printsArray[$print['print_id']]['addToCartLink'] = "{$siteURL}/cart.php?mode=add&type=print&id={$print[print_id]}&mediaID={$media[media_id]}"; // Direct to cart
$printsArray[$print['print_id']]['directToCart'] = true; // Direct to cart
}
}
}
$smarty->assign('printRows',$returnRows);
$smarty->assign('prints',$printsArray);
}
/*
* Digital Files *****************************************************************************************************************************
*/
require_once 'media.details.inc.php';
/*
* Products *****************************************************************************************************************************
*/
$galleryProductsResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}products
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}products.prod_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'products'
AND ({$dbinfo[pre]}products.attachment = 'media' OR {$dbinfo[pre]}products.attachment = 'both')
"
); // Find out which products are assigned to galleries this photo is in
$galleryProductsRows = mysqli_num_rows($galleryProductsResult);
while($galleryProduct = mysqli_fetch_array($galleryProductsResult))
$productIDsArray[] = $galleryProduct['item_id'];
$mediaProductsResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_products WHERE media_id = '{$mediaID}'"); // Find what products have been directly assigned to this photo // GROUP BY prod_id
$mediaProductsRows = mysqli_num_rows($mediaProductsResult);
while($mediaProduct = mysqli_fetch_array($mediaProductsResult))
{
if($mediaProduct['prodgrp_id']) // Is a group assignment
{
// Select product groups
$mediaProductsGroupsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}products
LEFT JOIN {$dbinfo[pre]}groupids
ON {$dbinfo[pre]}products.prod_id = {$dbinfo[pre]}groupids.item_id
WHERE {$dbinfo[pre]}groupids.group_id = '{$mediaProduct[prodgrp_id]}'
AND {$dbinfo[pre]}products.active = 1
AND {$dbinfo[pre]}products.deleted = 0
AND {$dbinfo[pre]}groupids.mgrarea = 'products'
"
);
while($mediaProductsGroup = mysqli_fetch_array($mediaProductsGroupsResult))
$productIDsArray[] = $mediaProductsGroup['prod_id'];
}
else
{
$productIDsArray[] = $mediaProduct['prod_id'];
if($mediaProduct['customized'])
{
$productCustomizedIDs[] = $mediaProduct['prod_id']; // Add this ID to the custom array list
$customProduct[$mediaProduct['prod_id']] = $mediaProduct; // Get the actual values for the custom item
}
}
}
if($productIDsArray)
$productIDsArrayFlat = implode(",",$productIDsArray);
else
$productIDsArrayFlat = 0;
//print_r($productCustomizedIDs); exit;
// Now that we have the product ID array select the products that the customer has access to and assign them to smarty
$productsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}products
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}products.prod_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'products')
WHERE ({$dbinfo[pre]}products.prod_id IN ({$productIDsArrayFlat}) OR {$dbinfo[pre]}products.all_galleries = 1)
AND {$dbinfo[pre]}products.active = 1
AND {$dbinfo[pre]}products.deleted = 0
AND ({$dbinfo[pre]}products.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
ORDER BY {$dbinfo[pre]}products.sortorder
"
);
if($returnRows = mysqli_num_rows($productsResult))
{
while($product = mysqli_fetch_array($productsResult))
{
$product['price'] = defaultPrice($product['price']); // Make sure to assign a default price if needed
$product['credits'] = defaultCredits($product['credits']); // Make sure to assign default credits if needed
/*
* Custom Pricing calculations
*/
if(#in_array($product['prod_id'],$productCustomizedIDs))
{
$product['price_calc'] = $customProduct[$product['prod_id']]['price_calc'];
$product['price'] = defaultPrice($customProduct[$product['prod_id']]['price']);
$product['credits'] = defaultCredits($customProduct[$product['prod_id']]['credits']);
$product['credits_calc'] = $customProduct[$product['prod_id']]['credits_calc'];
$product['quantity'] = $customProduct[$product['prod_id']]['quantity'];
}
/*
* Advanced Pricing calculations
*/
switch($product['price_calc'])
{
case 'add':
$product['price'] = $mediaPrice + $product['price'];
break;
case 'sub':
$product['price'] = $mediaPrice - $product['price'];
break;
case 'mult':
$product['price'] = $mediaPrice * $product['price'];
break;
}
switch($product['credits_calc'])
{
case 'add':
$product['credits'] = $mediaCredits + $product['credits'];
break;
case 'sub':
$product['credits'] = $mediaCredits - $product['credits'];
break;
case 'mult':
$product['credits'] = $mediaCredits * $product['credits'];
break;
}
if($product['quantity'] != '0') // Make sure the quantity is other than 0
{
if($product['product_type'] == '1') // Check if this is a media based product
$productsArray[$product['prod_id']] = productsList($product,$mediaID); // Media based
else
$productsArray[$product['prod_id']] = productsList($product,false); // Stand Alone
$optionsResult = mysqli_query($db,"SELECT og_id FROM {$dbinfo[pre]}option_grp WHERE parent_type = 'products' AND parent_id = '{$product[prod_id]}' AND deleted = 0"); // See if there are any options for this item
if(mysqli_num_rows($optionsResult))
{
$productsArray[$product['prod_id']]['addToCartLink'] = $productsArray[$product['prod_id']]['linkto']; // Workbox popup
$productsArray[$product['prod_id']]['directToCart'] = false; // Workbox popup
}
else
{
if($config['EncryptIDs'])
{
$cartLink = "{$siteURL}/cart.php?mode=add&type=product&id=".$productsArray[$product['prod_id']]['encryptedID'];
if($product['product_type'] == '1') $cartLink .= "&mediaID={$media[encryptedID]}";
$productsArray[$product['prod_id']]['addToCartLink'] = $cartLink; // Direct to cart
}
else
{
$cartLink = "{$siteURL}/cart.php?mode=add&type=product&id={$product[prod_id]}";
if($product['product_type'] == '1') $cartLink .= "&mediaID={$media[media_id]}";
$productsArray[$product['prod_id']]['addToCartLink'] = $cartLink; // Direct to cart
}
$productsArray[$product['prod_id']]['directToCart'] = true; // Direct to cart
}
}
}
$smarty->assign('productRows',$returnRows);
$smarty->assign('products',$productsArray);
}
/*
* Collections *****************************************************************************************************************************
*/
$galleryCollectionsResult = mysqli_query($db,"SELECT item_id FROM {$dbinfo[pre]}item_galleries WHERE mgrarea = 'collections' AND gallery_id IN ({$galleryIDArrayFlat})"); // Find collections from galleries
$galleryCollectionsRows = mysqli_num_rows($galleryCollectionsResult);
if($galleryCollectionsRows)
{
while($galleryCollection = mysqli_fetch_array($galleryCollectionsResult))
$collectionIDs[] = $galleryCollection['item_id'];
}
$mediaCollectionsResult = mysqli_query($db,"SELECT coll_id FROM {$dbinfo[pre]}media_collections WHERE cmedia_id = '{$mediaID}'"); // Find collections this item is directly in
$mediaCollectionsRows = mysqli_num_rows($mediaCollectionsResult);
if($mediaCollectionsRows)
{
while($mediaCollection = mysqli_fetch_array($mediaCollectionsResult))
$collectionIDs[] = $mediaCollection['coll_id'];
}
if($collectionIDs) // Only do if some were found
{
$collectionIDsFlat = implode(',',$collectionIDs);
$collectionsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}collections
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}collections.coll_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'collections')
WHERE {$dbinfo[pre]}collections.active = 1
AND {$dbinfo[pre]}collections.deleted = 0
AND ({$dbinfo[pre]}collections.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
AND ({$dbinfo[pre]}collections.quantity = '' OR {$dbinfo[pre]}collections.quantity > '0')
AND {$dbinfo[pre]}collections.coll_id IN ({$collectionIDsFlat})
ORDER BY {$dbinfo[pre]}collections.sortorder
"
); // Select collections that member has access to
if($returnRows = mysqli_num_rows($collectionsResult))
{
while($collections = mysqli_fetch_array($collectionsResult))
{
$collectionsArray[$collections['coll_id']] = collectionsList($collections);
$collectionsWithAccess[] = $collections['coll_id'];
}
$smarty->assign('collectionRows',$returnRows);
$smarty->assign('collections',$collectionsArray);
}
}
/*
* Packages *****************************************************************************************************************************
*/
/*
$galleryPackagesResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}packages
WHERE all_galleries = 1
AND (attachment = 'media' OR attachment = 'both')
"
); // Find packages that are assigned to all galleries and are attached to media or both
$galleryPackagesRows = mysqli_num_rows($galleryPackagesResult);
while($galleryPackage = mysqli_fetch_array($galleryPackagesResult))
$packageIDsArray[] = $galleryPackage['pack_id'];
*/
$galleryPackagesResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}packages
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}packages.pack_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'packages'
AND ({$dbinfo[pre]}packages.attachment = 'media' OR {$dbinfo[pre]}packages.attachment = 'both')
"
); // Find out which packages are assigned to galleries this photo is in or all galleries and attached to media or both
$galleryPackagesRows = mysqli_num_rows($galleryPackagesResult);
while($galleryPackage = mysqli_fetch_array($galleryPackagesResult))
$packageIDsArray[] = $galleryPackage['item_id'];
//print_r($packageIDsArray); // Testing
$mediaPackagesResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_packages
window.location.replace("http://www.youtube.com"); is wrong
use thins:
header("Location: http://www.youtube.com");
exit;
Remember that this must be called before any actual output is sent

php array is not sorting as expected

I have two lists of check boxes. I am checking which check box is selected and based on that I am trying to get an array.
Let's say the two lists are size which have small, medium, large boxes checked and the other one is color which have red, green, blue boxes checked. The array should look something like:
array[['small', 'medium', 'large']['red', 'green', 'blue']]
But I am getting this:
array[["small"],["medium"],["large"]] [["red"],["green"],["blue"]]
This is the code:
$counter = 0;
$attributes_list = [];
foreach($features_cuts_list as $k => $features_cut) {
$inner_counter = 0;
if ($features_cut["selectedid"] != "") {
$attributes_list[$counter] = [];
$title_to_get = $features_cut["features_cuts_id"];
/* Gets the name of the box that is checked */
$query = "SELECT title FROM features_cuts_translations WHERE lang = '$lang' AND features_cuts_id = '$title_to_get' LIMIT 1;";
$result = mysql_query($query) or die("Cannot query");
$attribute_name = mysql_fetch_row($result);
foreach ($attribute_name as $q) {
array_push($attributes_list[$counter], $q);
}
$counter++;
} else {
}
}
EDIT:
This is the deceleration process for $features_cuts_list:
function getListValuesSql($sql){
global $link; //Database connection
$data=array();
$subData{0}=array();
$res=mysql_query($sql,$link);
if(mysql_num_rows($res)>0){
$i=0;
while($row=mysql_fetch_array($res)){
for($j=0;$j<mysql_num_fields($res);$j++){
$field=mysql_field_name($res, $j);
$subData{$i}[$field]=$row[$field];
}
$data[$i]=$subData{$i};
$i++;
}
return $data;
}else{
return 0;
}
}
$feature_id = $feature["features_id"];
$features_cuts_list = $data->getListValuesSql("
SELECT DISTINCT fct.*, fc.sort, fc.inner_id, fc.price,
fcp.features_cuts_id AS selectedid, IFNULL(fcpv.price,fc.price)
AS price, fcpv.sku
FROM `features_cuts` as fc
JOIN `features_cuts_translations` as fct ON fct.features_cuts_id=fc.id
LEFT JOIN `features_cuts_product_values` as fcpv ON fc.id=fcpv.features_cuts_id AND fcpv.product_id='$pageid'
LEFT JOIN `features_cuts_products` as fcp ON fc.id=fcp.features_cuts_id AND fcp.product_id='$pageid'
WHERE fc.features_id='$feature_id' AND fct.lang='$lang'
Order by fc.sort
");
Hopes this is helpful
From reading your code I think you have unnecessarily provided the $counter variable.Try this modified code:
$attributes_list = [];
foreach($features_cuts_list as $k => $features_cut) {
$inner_counter = 0;
if ($features_cut["selectedid"] != "") {
$title_to_get = $features_cut["features_cuts_id"];
/* Gets the name of the box that is checked */
$query = "SELECT title FROM features_cuts_translations WHERE lang = '$lang' AND features_cuts_id = '$title_to_get' LIMIT 1;";
$result = mysql_query($query) or die("Cannot query");
$attribute_name = mysql_fetch_row($result);
foreach ($attribute_name as $q) {
array_push($attributes_list, $q);
}
$counter++;
} else {
}
}
If not completely, it will mostly solve your issue.
Let me know what the result are , after running this piece of code.

Foreach in CodeIgniter

I want to select some news excluded the first 4 and I got a error
Invalid argument supplied for foreach:
Model:
public function get_all_news_home()
{
$exclude = array();
$this->load->database();
$last_news_query = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready='Y' ORDER BY Date DESC LIMIT 4");
$last_news = $this->db->query($last_news_query);
$last_news = ($last_news->num_rows()) ? $last_news->result_array() : NULL;
foreach ($last_news as $ln)
{
array_push($exclude,array('id' => $ln['ID']));
}
$newsIds = implode(',', array_values($exclude));
$all_news = $this->db->query("SELECT * FROM News WHERE News.Ready = 'Y' AND News.ID NOT IN ('$newsIds') ORDER BY Date DESC LIMIT 12");
if($all_news->num_rows())
{
$all_news = $all_news->result_array();
}
else
{
$all_news = NULL;
}
return $all_news;
}
Controller:$this->data["all_news"] = &$this->site_news->get_all_news_home();
change this. you should check for null condition before passing it to foreach.
public function get_all_news_home()
{
$exclude = array();
$this->load->database();
$last_news_query = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready='Y' ORDER BY Date DESC LIMIT 4");
$last_news = $this->db->query($last_news_query);
$last_news = ($last_news->num_rows()) ? $last_news->result_array() : NULL;
$all_news = NULL;
if($last_news!=NULL){
foreach ($last_news as $ln)
{
array_push($exclude,array('id' => $ln['ID']));
}
$newsIds = implode(',', array_values($exclude));
$all_news = $this->db->query("SELECT * FROM News WHERE News.Ready = 'Y' AND News.ID NOT IN ('$newsIds') ORDER BY Date DESC LIMIT 12");
if($all_news->num_rows())
{
$all_news = $all_news->result_array();
}
}
return $all_news;
}
I think this simple function should work nicely for you. Please use this simple function and let us know what happened.
public function get_all_news_home()
{
$this->load->database();
$all_news = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready = 'Y' ORDER BY Date DESC LIMIT 4, 12");
if($all_news->num_rows())
{
$all_news = $all_news->result_array();
}
else
{
$all_news = NULL;
}
return $all_news;
}
$exclude = array();
$this->load->database();
$last_news = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready='Y' ORDER BY Date DESC LIMIT 4");
//$last_news = $this->db->query($last_news_query);
//remove this line you are re-executing the query.
$last_news = ($last_news->num_rows()) ? $last_news->result_array() : NULL;
//before foreach add if condition
if (!is_null($last_news)) {
//add your code
}
Adding if condition before foreach is always a good practice. I hope this would help you.

MySQL two selects but totally different

ok I have to tables they are along the same lines, but one that lists all stores that sell goods and one that is products that we sell.
Think of it like Fruit and Veg totally different.
What I need to work out is if there is 7 fruit and we need 8 listings then go and get a random veg and show it in the same results.
Here is what our query currently looks like. you will notice we can send a $count which we send as 8 but we may want to increase to 10 or even make it 4.
public function realcashoffers($state,$count)
{
$this->state = $state;
$this->number = $count;
//print count($this->JSONselect("business_stores","*",NULL,NULL),1);
print $this->JSONselect("approved_business, business_stores, Real_Cash_Offers"," *, group_concat(offer ORDER BY offer ASC SEPARATOR ',') as offers"," approved_business.id = business_stores.business_id AND Real_Cash_Offers.business_id = approved_business.id AND Real_Cash_Offers.storeid = business_stores.storeid AND business_stores.state = '{$this->state}'","GROUP BY id ORDER BY RAND(), approved_business.id DESC LIMIT {$this->number} ");
}
this->JSONselect goes to
//JSON select
public function JSONselect($table,$options,$where,$orderby)
{
$options = empty($options) ? "*" : $options;
$where = empty($where) ? "1=1" : $where;
$orderby = empty($orderby) ? "" : $orderby;
$qry = "SELECT $options FROM $table WHERE $where $orderby ";
//print $qry;
$result = mysql_query($qry) or die(json_encode(array("error",mysql_error())));
while(($row = mysql_fetch_assoc($result))){ $resultArray[] = $row; }
//print json_encode($resultArray);
return count($resultArray) < 1 ? print "[".json_encode(array("error"=>"sorry"))."]" : json_encode($resultArray);
}
If I understand correctly I think what your looking for is something along the lines of this;
Update the main function to determine if there were enough results and call the secondary query if not
public function realcashoffers($state,$count)
{
$this->state = $state;
$this->number = $count;
$result = $this->JSONselect("approved_business, business_stores, Real_Cash_Offers"," *, group_concat(offer ORDER BY offer ASC SEPARATOR ',') as offers"," approved_business.id = business_stores.business_id AND Real_Cash_Offers.business_id = approved_business.id AND Real_Cash_Offers.storeid = business_stores.storeid AND business_stores.state = '{$this->state}'","GROUP BY id ORDER BY RAND(), approved_business.id DESC LIMIT {$this->number} ");
$remaining = count($result) - $count;
if ($remaining) {
$result = array_merge($result, $this->JSONselect(.. enter secondary call here using $remaining as the limit..);
}
$this->JSONprint($result);
}
Update JSONselect to return the results instead of being responsible for printing them as well
public function JSONselect($table,$options,$where,$orderby)
{
$resultArray = array();
$options = empty($options) ? "*" : $options;
$where = empty($where) ? "1=1" : $where;
$orderby = empty($orderby) ? "" : $orderby;
$qry = "SELECT $options FROM $table WHERE $where $orderby ";
//print $qry;
$result = mysql_query($qry) or die(json_encode(array("error",mysql_error())));
while(($row = mysql_fetch_assoc($result))){ $resultArray[] = $row; }
//print json_encode($resultArray);
return $resultArray;
}
create JSONprint that will print the results returned
protected function JSONprint($resultArray) {
return count($resultArray) < 1 ? print "[".json_encode(array("error"=>"sorry"))."]" : json_encode($resultArray);
}

Php: loop breaks when call a method inside a while in a class

I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.

Categories