sprintf and php - sql

The following function gives all the related data except artist_id, when run I have checked all elements in the database and ok.
If I change the artist_id to an actual 'id' it shows in the result of the function as WHERE artist_id = 4 AND........
Confess I do not understand what is causing this.
Result of the function:
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE artist_id = AND member_id = 1 AND
image_album_id = 160
<?php
function get_data_nxtprv($fields, $where) {
$return = FALSE;
// Template
$template = "SELECT %s "
. "FROM album_images "
. "WHERE artist_id = " . $artist_id. "
AND member_id = ".$_SESSION['member_id']." %s";
// Current record
$sql = sprintf($template, $fields, $where);
$query = mysql_query($sql);
$query_result = mysql_fetch_assoc($query);
//print_r($sql);
// If data has been found
if ($query_result)
{
$return = $query_result;
}
return $return;
?>

I am not entirely sure I understand your question. But I noticed that your function uses three input variables:
$artist_id, $fields, $where
But $artist_id is not getting passed as an argument.
You would need to modify the function call:
function get_data_nxtprv($artist_id, $fields, $where)

There is an error in your SQL
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE artist_id = AND member_id = 1 AND
image_album_id = 160
should it not be
SELECT `image_album_id`, `member_id`, `artist_id`, `albumname`, `ext`, `timestamp`
FROM album_images WHERE member_id = 1 AND
image_album_id = 160
if artist_id is one of the fields you're looking for?

Related

posts_orderby not displaying the posts

I would like to customize my wordpress search page
First, i used the "posts_where" to modify the clause
function search_posts_where ($where) {
global $wp_query, $wpdb;
// Searching and not in admin
if (!is_admin() && $wp_query->is_search && isset($wp_query->query_vars['s'])) {
// Tables names
$post_title = "{$wpdb->prefix}posts.post_title";
$post_excerpt = "{$wpdb->prefix}posts.post_excerpt";
$post_content = "{$wpdb->prefix}posts.post_content";
$post_type = "{$wpdb->prefix}posts.post_type";
$post_status = "{$wpdb->prefix}posts.post_status";
$post_author = "{$wpdb->prefix}posts.post_author";
$post_ID = "{$wpdb->prefix}posts.ID";
$post_date = "{$wpdb->prefix}posts.post_date";
// Get the 's' parameters
$wp_query->query_vars['s'] ? $search_text = $wp_query->query_vars['s'] : $search_text = 'IS NULL';
// Write the where clause
$where = " AND ((($post_title LIKE '%$search_text%')";
$where .= " OR ($post_excerpt LIKE '%$search_text%')";
$where .= " OR ($post_content LIKE '%$search_text%')))";
$where .= " AND $post_type IN ('parcours')";
$where .= " AND $post_status = 'publish'";
$where .= " GROUP BY $post_ID";
}
return $where;
}
add_filter('posts_where', 'search_posts_where', 10, 2);
It works fine. All posts belonging to my custom post type 'parcours' are shown, depending on what I entered for the 's' query.
Second, i used the "posts_join" to add the meta table (not used yet !)
function search_posts_join ($join) {
global $wp_query, $wpdb;
// Searching and not in admin
if (!is_admin() && $wp_query->is_search && isset($wp_query->query_vars['s'])) {
// Tables names
$post_meta = "{$wpdb->prefix}postmeta";
$post_ID = "{$wpdb->prefix}posts.ID";
$post_meta_ID = "{$wpdb->prefix}postmeta.post_id";
// Join clause
$join .= "LEFT JOIN $post_meta ON ($post_ID = $post_meta_ID)";
}
return $join;
}
add_filter('posts_join', 'search_posts_join', 10, 2);
Still works perfectly !
Now the problem, i would like to order my posts in ascending direction (default is descending). So, i added the "posts_orderby" hook.
function search_posts_orderby ($orderby) {
global $wp_query, $wpdb;
// Searching and not in admin
if (!is_admin() && $wp_query->is_search) {
// Tables names
$post_title = "{$wpdb->prefix}posts.post_title";
$post_date = "{$wpdb->prefix}posts.post_date";
$post_ID = "{$wpdb->prefix}posts.ID";
// Order by clause
$orderby .= " ORDER BY $post_title ASC,";
$orderby .= " $post_date DESC";
}
return $orderby;
}
add_filter('posts_orderby', 'search_posts_orderby', 10, 2);
And here is the problem. All posts disapeared. Removing the "orderby" and they come back.
Looking at the SQL query, i have
"SELECT SQL_CALC_FOUND_ROWS wp_128444_posts.* FROM wp_128444_posts LEFT JOIN wp_128444_postmeta ON (wp_128444_posts.ID = wp_128444_postmeta.post_id) WHERE 1=1 AND (((wp_128444_posts.post_title LIKE '%tour%') OR (wp_128444_posts.post_excerpt LIKE '%tour%') OR (wp_128444_posts.post_content LIKE '%tour%'))) AND wp_128444_posts.post_type IN ('parcours') AND wp_128444_posts.post_status = 'publish' GROUP BY wp_128444_posts.ID ORDER BY wp_128444_posts.post_title LIKE '{5a35f6e9144541f93e08829126b2cb633436cebf95d774062fff749a12e6a465}tour{5a35f6e9144541f93e08829126b2cb633436cebf95d774062fff749a12e6a465}' DESC, wp_128444_posts.post_date DESC ORDER BY wp_128444_posts.post_title ASC, wp_128444_posts.post_date DESC LIMIT 0, 6"
I don't know why WP is adding the default ORDER BY, that i don't want.
Is is possible to remove it ?
I tried to replace my hook with "pre_get_posts" hook
function order_posts_by_title( $query ) {
if ( $query->is_search() && $query->is_main_query() ) {
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'order_posts_by_title' );
With this hook, it works !! Sounds very strange to me
Any explanation ?
Thanks

Query giving double result instead of single

I have two tables: products and current_product_attribute_values
I have tried a join query to filter them as per attribute selected by the user but when I try this with an additional condition it gives me 2 results instead of one it is including the first one which is not matching as per query:
select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
here is my laravel Controller code :
$all = Input::all();
$q = Input::get('search_text');
$att_val = Input::get('attribute_value');
$subcat = Input::get('subcat_id');
$subcat_name = DB::table('subcategories')->where('id', $subcat)->value('subcategory_name');
$brandname = DB::table('brands')->where('subcat_id', $subcat)->value('brand_name');
$brand_id = DB::table('brands')->where('subcat_id', $subcat)->value('id');
$product_count = DB::table('products')->where('brand_id', $brand_id)->count();
if ($q != "") {
// getting multiple same name params
$query = DB::table('products');
$query->join('current_product_attribute_values', 'products.id', '=', 'current_product_attribute_values.product_id');
$j = 0;
foreach ($all as $key => $values) {
//echo 'my current get key is : ' . urldecode($key). '<br>';
if ($key == $name[$j]) {
$query->where('current_product_attribute_values.attribute_id', '=', $att_id_value[$j]);
echo'<br>';
print_r($query->toSql());
echo'<br>';
//echo '<br> key matched and have some value : <br>';
//echo count($values);
if (count($values) >= 1) {
//echo '<br> it has array inside <br>';
foreach ($values as $val) {
// or waali query in same attribute
echo'<br>';
$query->orwhere('current_product_attribute_values.attribute_value_id', '=', $val);
print_r($query->toSql());
echo'<br>';
}
}
$j++;
}
}
$records = $query->toSql();
$query->where('product_name', 'LIKE', '%' . $q . '%');
$records = $query->toSql();
print_r($records);
$products = $query->paginate(10)->setPath('');
$pagination = $products->appends(array(
'q' => Input::get('q')
));
if (count($products) > 0) {
$filters = DB::table('product_attributes')->where('subcategory_id', $subcat)->get(['attribute_title']);
} else {
$filters = array();
}
$categories = categories::where('add_to_menu', 1)->with('subcategories')->with('brands')->get();
$categoryhome = categories::where('add_to_menu', 1)->with('subcategories')->get();
return view('searchfilter')
->with('productsdata', $products)
->with('filtersdata', $filters)
->with('categories', $categories)
->with('categorieshome', $categoryhome)
->with('subcat_name', $subcat_name)
->with('subcat_id', $subcat)
->with('brandname', $brandname)
->with('product_count', $product_count)
->with('querytext', $q);
}
return 'No Details found. Try to search again !';
its easier if you use raw sql as calling db select function. ex:
$query=DB::select("select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
");
indeed you can concat vars in raw sql if you need to, ex:
$queryBrands = "select id from brands where subcat_id =".$subcat;
//echo $queryBrands
$queryBrands = DB::select($queryBrands);
By looking at your tables, product table with id value 17 has two records in table current_product_attribute_values in column product_id (I assume this column is used as foreign key to product table).
With select *, you select all of the columns from both tables. So it would most likely cause your query to return multiple records.
My suggestions:
Only select the columns you need. Avoid using select * in the long run, i.e. select product.id, product.description, current_product_attribute_values.attribute_values ......
Make use of GROUP BY
Hope these helps.

Wordpress: Check data by using get_results

I have problem to check data if its found or not, Bellow i have table in Wordpress called (postmeta), and store data like :
meta_id : 27327
post_id : 4876
meta_key : rtb
meta_value : a:20:{s:5:"party";i:1;s:5:"email";s:18:"test#gmail.com";s:5:"phone";s:10:"05921655517";s:8:"catofres";s:6:"single";s:9:"tabletype";s:8:"openarea";s:14:"validationcode";i:8407704;s:11:"frindsname1";s:0:"";s:13:"frindsmobile1";s:0:"";s:11:"frindsname2";s:0:"";s:13:"frindsmobile2";s:0:"";s:11:"frindsname3";s:0:"";s:13:"frindsmobile3";s:0:"";s:11:"frindsname4";s:0:"";s:13:"frindsmobile4";s:0:"";s:11:"frindsname5";s:0:"";s:13:"frindsmobile5";s:0:"";s:11:"frindsname6";s:0:"";s:13:"frindsmobile6";s:0:"";s:15:"date_submission";i:1525176468;s:2:"ip";s:10:"37.8.85.11";}
Now the problem how can do SQL query that check if the data (test#gmail.com , 8407704) found it this table or not ,,,
I try this query :
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `meta_key` = 'rtb' ", OBJECT );
But I could not complete the check in the Query
global $wpdb;
$metas = $wpdb->get_results(
$wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta where meta_key = %s", 'rtb')
);
print_r($metas);
try also
if ( metadata_exists( 'post', $post_id, 'rtb' ) ) {
$meta_value = get_post_meta( $post_id, 'rtb', true );
}

take value after execute query

Im new to Codeigniter and its developing. i have tested a query succefully. But when i try to take voteid value im getting errors please help me.
$query=$this->db->query("SELECT voteid FROM Questions WHERE questionid = '$questionid'");
echo $query->voteid; //im getting errors here.
Var_dump value of query
object(CI_DB_mysql_result)#18 (8) {
["conn_id"]=>
resource(30) of type (mysql link persistent)
["result_id"]=>
resource(39) of type (mysql result)
["result_array"]=>
array(0) {
}
["result_object"]=>
array(0) {
}
["custom_result_object"]=>
array(0) {
}
["current_row"]=>
int(0)
["num_rows"]=>
int(1)
["row_data"]=>
NULL
Error
Severity: Notice
Message: Undefined property: CI_DB_mysql_result::$voteid
Filename: models/questions_model.php
$query=$this->db->query("SELECT * FROM Questions WHERE questionid = '$id'");
echo $query->row()->voteid;
try this it should work
Your query returns nothing because it's incorrect. Try: "SELECT voteid FROM Questions WHERE questionid = " . $questionid (I assume that $questionid is a variable of integer type)
Try this type of writing your queries:
$this->db->select( 'voteid' );
$this->db->from ( 'Questions' );
$this->db->where ( 'questionid', $questionid );
$result = $this->db->get( );
if ( $result->num_rows( ) > 0 )
{
$row = $result->row( );
$row->voteid;
}
Try this:
$query=$this->db->query( "SELECT voteid FROM Questions WHERE questionid = $questionid" );
$row = $query->row();
return $row->voteid;
Using '$questionid' means that your variable is a string, but in this case it's an integer.

Magento API: Assigning preexisting simple products to configurable products

I've got a client database with a large range of stock items, which are being uploaded to Magento as simple products.
Now I need to group them up and assign them to configurable products with their size and colour being their configurable attributes.
The Magento API has a Product_Link class, with a promising looking method: catalogue-product-link.assign (link), but I can't for the life of me figure out what arguments I need to make it work with configurable products, providing this is how assign was meant to be used.
Well the notes here helped me get this running. So I thought I'd share with you the code to add a simple product to an existing Configurable Product.
This code assumes the simple product is a valid one to add, I'm not sure what would happen if it wasn't.
private function _attachProductToConfigurable( $_childProduct, $_configurableProduct ) {
$loader = Mage::getResourceModel( 'catalog/product_type_configurable' )->load( $_configurableProduct );
$ids = $_configurableProduct->getTypeInstance()->getUsedProductIds();
$newids = array();
foreach ( $ids as $id ) {
$newids[$id] = 1;
}
$newids[$_childProduct->getId()] = 1;
$loader->saveProducts( $_configurableProduct->getId(), array_keys( $newids ) );
}
The code from the accepted answer by Scimon does not work anymore in recent versions of magento (at least in 1.7). But fortunately, you need just a small fix to get it working again:
private function _attachProductToConfigurable( $_childProduct, $_configurableProduct ) {
$loader = Mage::getResourceModel( 'catalog/product_type_configurable' )->load( $_configurableProduct, $_configurableProduct->getId() );
$ids = $_configurableProduct->getTypeInstance()->getUsedProductIds();
$newids = array();
foreach ( $ids as $id ) {
$newids[$id] = 1;
}
$newids[$_childProduct->getId()] = 1;
//$loader->saveProducts( $_configurableProduct->getid(), array_keys( $newids ) );
$loader->saveProducts( $_configurableProduct, array_keys( $newids ) );
}
I'm working on doing this right now.
So far I've found these items helpful as references:
http://snippi.net/magento-programmatically-add-configurable-product-color-api
http://www.omnisubsole.com/blog/2009/07/01/configurable-products-in-magento.html
http://www.magentocommerce.com/boards/viewthread/6941/P30/
I'll post my code so far, and hopefully update it once it works..
// Set 'item_size' as the super attribute # choose your own attribute!
// this is the 'choose-able' field that differenciates products
$super_attributes=array( Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product','item_size')
->getData('attribute_id')
);
$product_collection=Mage::getModel('catalog/product')->getCollection();
// Fetch configurable orders
$product_collection->addFieldToFilter('type_id',Array('eq'=>"configurable"));
#$product_collection->addFieldToFilter('sku',Array('eq'=>"ASMCL000002"));
$product_collection->addAttributeToSelect('*');
$count=0;
foreach($product_collection as $product) {
$sku = $product->getSku();
echo "SKU: $sku\n";
$simple_children_collection = Mage::getModel('catalog/product')->getCollection();
$simple_children_collection->addAttributeToSelect('*');
$simple_children_collection->addFieldToFilter('sku',Array('like'=>$sku . "-%"));
echo "children: ";
foreach($simple_children_collection as $child) {
$child_sku = $child->getSku();
echo "$child_sku ";
#visiblity should be 'nowhere'
}
echo "\n";
if (!$product->getTypeInstance()->getUsedProductAttributeIds()) {
# This is a new product without the Configurable Attribue Ids set
$product->getTypeInstance()
->setUsedProductAttributeIds( $super_attributes );
//$product->setConfigurableAttributesData(array($_attributeData));
$product->setCanSaveConfigurableAttributes(true); # Not sure if this is needed.
$product->setConfigurableProductsData(''); # Use this to add child products.
}
$count++;
try {
$product->save();
$productId = $product->getId();
echo $product->getId() . ", $sku updated\n";
}
catch (Exception $e){
echo "$sku not added\n";
echo "exception:$e";
}
}
echo "\nCount is $count\n";
Okay, this uses 'item_size' as the attribute that differentiates the "simple" products. Also, this assumes that the "configurable" parent SKU is the root of the child SKU. For example, ABC001 is the parent while ABC001-SMALL and ABC001-LARGE are the simple children.
Hope that helps someone.
I this is an un-educated guess, but I think what your asking for can't be done with the existing API. You will have to write your own or just got directly to the DB.
Here is the hack-y way that I did this straight with PHP. There are three related tables. I was using color and size as my attributes.
My parent products (configurable) don't actually exist in my catalog. They are essentially model level and then the products are the SKU level.
So LIKE 'parentproductsku%' works out for the children.
$query1 = "SELECT * FROM mage_catalog_product_entity WHERE type_id= 'configurable'";
//Find the parent id
$statusMessage = "Ok, found a product with a confgurable attribute";
$result1 = $this->runQuery($query1, "query1", $statusMessage);
while ($row1 = mysql_fetch_assoc($result1)) { //entering the first loop where products are configurable
$this->parentId = $row1['entity_id'];
$this->parentSku = $row1['sku'];
echo "The SKU was $this->parentSku" . "<br />";
//insert these into the link table for association
$query2 = "SELECT * FROM mage_catalog_product_entity WHERE type_id= 'simple' AND sku LIKE '" . $this->parentSku . "%';";
// find the child ids that belong to the parent
$statusMessage = "Found some children for $this->parentSku";
$result2 = $this->runQuery($query2, "query2", $statusMessage);
while ($row2 = mysql_fetch_assoc($result2)) {//entering the second loop where SKU is like model sku
$this->childId = $row2['entity_id'];
$this->childSku = $row2['sku'];
echo "Now we're working with a child SKU $this->childSku" . "<br />";
//"REPLACE INTO catalog_product_super_attribute SET product_id='".$product->entity_id."', attribute_id='".$attribute->attribute_id."', position='".$position."'";
$query3 = "REPLACE INTO mage_catalog_product_super_attribute (product_id, attribute_id, position) VALUES ('" . $this->childId . "', '76', '0');";
$message3 = "Inserted attribute for color for ID $this->childId SKU $this->childSku";
$result3 = $this->runQuery($query3, "query3", $message3);
$query4 = "REPLACE INTO mage_catalog_product_super_attribute_label (product_super_attribute_id, store_id, use_default, value) VALUES (LAST_REPLACE_ID(), '0', '0', 'Color');";
$message4 = "Inserted attribute for Color SKU $this->childSku ID was $this->db->insert_id";
$result4 = $this->runQuery($query4, "query4", $message4);
$query5 = "REPLACE INTO mage_catalog_product_super_attribute (product_id, attribute_id, position) VALUES ('" . $this->childId . "', '529', '0');";
$message5 = "Inserted attribute for Product Size SKU $this->childSku";
$result5= $this->runQuery($query5, "query5", $message5);
$query6 = "REPLACE INTO mage_catalog_product_super_attribute_label (product_super_attribute_id, store_id, use_default, value) VALUES (LAST_REPLACE_ID(), '0', '0', 'Size');";
$message6 = "Inserted attribute for Size SKU $this->childSku ID was $this->db->insert_id";
$result6 = $this->runQuery($query6, "query6", $message6);
$query7 = "REPLACE INTO mage_catalog_product_super_link (product_id, parent_id) VALUES ('" . $this->childId . "', '" . $this->parentId . "');";
$message7 = "Inserted $this->childId and $this->parentId into the link table";
$result7 = $this->runQuery($query7, "query7", $message7);
$query8 = "REPLACE INTO mage_catalog_product_relation (parent_id, child_id) VALUES ('" . $this->parentId . "', '" . $this->childId . "');";
$message8 = "Inserted $this->childId and $this->parentId into the link table";
$result8 = $this->runQuery($query8, "query8", $message8);
} //end while row 2 the child ID
} //end while row 1 the parent id
Surprisingly, this works, if all your simple products share the same price:
$childProducts = $configurable->getTypeInstance(true)->getUsedProductIds($configurable);
// Don't add this product if it's already there
if(!in_array($child->getId(), $childProducts)) {
$childProducts[] = $child->getId();
}
$existingIds = $configurable->getTypeInstance(true)->getUsedProductAttributeIds($configurable);
$newAttributes = array();
foreach($configurable->getTypeInstance(true)->getSetAttributes($configurable) as $attribute) {
if(!in_array($attribute->getId(), $existingIds) && $configurable->getTypeInstance(true)->canUseAttribute($attribute)
&& $child->getAttributeText($attribute->getAttributeCode())) {
// Init configurable attribute
$configurableAtt = Mage::getModel('catalog/product_type_configurable_attribute')
->setProductAttribute($attribute);
// Add new attribute to array
$newAttributes[] = array(
'id' => $configurableAtt->getId(),
'label' => $configurableAtt->getLabel(),
'position' => $attribute->getPosition(),
'values' => $configurableAtt->getPrices() ? $configurable->getPrices() : array(),
'attribute_id' => $attribute->getId(),
'attribute_code' => $attribute->getAttributeCode(),
'frontend_label' => $attribute->getFrontend()->getLabel(),
);
}
}
if(!empty($newAttributes)) {
$configurable->setCanSaveConfigurableAttributes(true);
$configurable->setConfigurableAttributesData($newAttributes);
}
$configurable->setConfigurableProductsData(array_flip($childProducts));
$configurable->save();
#aeno's solution did not work for me, so I refined it a bit. This has been tested using a product instantiated via the Mage::getModel( 'catalog/product' )->load() method.
private function _attachProductToConfigurable( $childProduct, $configurableProduct )
{
$childIds = $configurableProduct->getTypeInstance()->getUsedProductIds();
$childIds[] = $childProduct->getId();
$childIds = array_unique( $childIds );
Mage::getResourceModel( 'catalog/product_type_configurable' )
->saveProducts( $configurableProduct, $childIds );
}