PDO Access Query - sql

Hi everyone I've some problems with a PDO query in access.
$result1 = $database->prepare('SELECT * FROM tblDestinazioni INNER JOIN tblRagioneSociale ON tblDestinazioni.id_cliente = tblRagioneSociale.id_cliente');
//$result1->execute(array(':nrags' => $rag, ':ndrags' => $nuovadest));
$result1->execute();
in this way it works, but i have to insert two more conditions... so:
$result1 = $database->prepare('SELECT * FROM tblDestinazioni INNER JOIN tblRagioneSociale ON tblDestinazioni.id_cliente = tblRagioneSociale.id_cliente WHERE tblDestinazioni.nome_dest=ndrags AND tblRagioneSociale.nomer=nrags');
$result1->execute(array(':nrags' => $rag, ':ndrags' => $nuovadest));
But it doesn't work (It returns to me a wrong result).
Please help me,
Thanks a lot
tblDestinazioni:
id_destinazioni INT AUTO_INCREMENT(PK)
id_cliente INT(FK)
nome_dest VARCHAR(30)
tblRagioneSociale:
id_cliente INT(PK)
rags VARCHAR(30)
more code:
<?php
$db_username = ''; //username
$db_password = ''; //password
$database_path = "Z:\\2017datiW.mdb";
$database = new PDO("odbc:DRIVER={Microsoft AccessDriver(*.mdb)}; DBQ=$database_path; Uid=$db_username; Pwd=$db_password;");
$rag=$_POST["rag"];
$nuovadest=$_POST["nuovadest"];
$result1 = $database->prepare('SELECT * FROM tblDestinazioni INNER JOIN tblRagioneSociale ON tblDestinazioni.id_cliente = tblRagioneSociale.id_cliente');
$result1->execute(array(':nrags' => $rag, ':ndrags' => $nuovadest));
?>

Related

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.

phalcon phql fetch vs fetch all

i am getting a fetchAll when using PHQL.
is there anyway to set it to just a fetch?
$result = $this->modelsManager->executeQuery ( $phql , [ "id" => $id ] );
i have to set the results to: return $result[0];
cheers.
try with:
$phql = "SELECT * FROM \Models\News AS n WHERE n.id = :id:";
$singleResult = $this->modelsManager->executeQuery($phql, ['id' => 3])->getFirst();

Yii2 subquery in Active Record

How can I convert this sql into active record query
SELECT * FROM `base_twitter` WHERE id NOT IN (SELECT base_id from base_followers)
Assuming that your models are named BaseTwitter and BaseFollower accordingly, this should work:
$subQuery = BaseFollower::find()->select('id');
$query = BaseTwitter::find()->where(['not in', 'id', $subQuery]);
$models = $query->all();
// SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
$subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
$query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
// subquery can also be a string with plain SQL wrapped in parenthesis
// SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
$subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
$query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
Try This Query
$models = BaseTwitter::find()->where('id NOT IN (SELECT base_id from base_followers)')->all();

Unknown column in WHERE clause using addExpressionFieldToSelect in Magento Collection

I've a magento grid. I'm preparing the collection this way:
protected function _prepareCollection()
{
$listingData = Mage::helper('M2ePro/Data_Global')->getValue('temp_data');
// Get collection products in listing
//--------------------------------
$collection = Mage::helper('M2ePro/Component_Amazon')->getCollection('Listing_Product');
$collection->addExpressionFieldToSelect(
'hello',
'sum({{prod_id}})',
array('prod_id' => '`main_table`.`product_id`')
);
$collection->getSelect()->distinct();
$collection->getSelect()->where("`main_table`.`listing_id` = ?",(int)$listingData['id']);
//--------------------------------
The resulting select is:
SELECT DISTINCT `main_table`.*, `second_table`.*, sum(`main_table`.`product_id`) AS `hello`, `cpe`.`sku` AS `magento_sku`, `cisi`.`is_in_stock`, `cpev`.`value` FROM `sm_m2epro_listing_product` AS `main_table` INNER JOIN `sm_m2epro_amazon_listing_product` AS `second_table` ON `second_table`.`listing_product_id` = `main_table`.`id` INNER JOIN `sm_catalog_product_entity` AS `cpe` ON (cpe.entity_id = `main_table`.product_id) INNER JOIN `sm_cataloginventory_stock_item` AS `cisi` ON (cisi.product_id = `main_table`.product_id AND cisi.stock_id = 1) INNER JOIN `sm_catalog_product_entity_varchar` AS `cpev` ON ( `cpev`.`entity_id` = `main_table`.product_id ) INNER JOIN `sm_eav_attribute` AS `ea` ON (`cpev`.`attribute_id` = `ea`.`attribute_id` AND `ea`.`attribute_code` = 'name') WHERE (`main_table`.`component_mode` = 'amazon') AND (`main_table`.`listing_id` = 3) AND (cpev.store_id = (SELECT MAX(`store_id`) FROM `sm_catalog_product_entity_varchar` WHERE (`entity_id` = `main_table`.`product_id`) AND (`attribute_id` = `ea`.`attribute_id`) AND (`store_id` = 0 OR `store_id` = 7)))
But the program fails on:
$this->addColumn('ASIN_duplicate', array(
'header' => Mage::helper('M2ePro')->__('Duplicated'),
'width' => '20px',
'index' => 'hello',
));
With "Unknown column ‘hello' in WHERE clause".
Cannot figure out where's the problem.

Piwik plugins

I'm building a plugin, and I want to have a Subtable, so that my users can click on the overview data, and display the data from there.
Following the code that I've been able to glean:
public function getCompanyList($idSite, $period, $date )
{
$dataTable = new Piwik_DataTable();
$query = Piwik_Query("SELECT cl.id, cl.company_name name, sf.id sf_id FROM sitedb.company_lookup cl INNER JOIN sitedb.storefronts sf ON cl.id = sf.company_id");
while ($row = $query->fetch()) {
$piwik_row = new Piwik_DataTable_Row;
$piwik_row->setSubTable( $this->getProductsForCompany($idSite, $period, $date, $row['id']) );
$piwik_row->setColumns( array('id' => $row['id'], 'Company Name' => $row['name']) );
$dataTable->addRow($piwik_row);
}
return $dataTable;
}
public function getProductsForCompany($idSite, $period, $date, $company_id )
{
if (!defined('PIWIK_ENABLE_DISPATCH')) define('PIWIK_ENABLE_DISPATCH', false);
if (!defined('PIWIK_ENABLE_ERROR_HANDLER')) define('PIWIK_ENABLE_ERROR_HANDLER', false);
require_once PIWIK_INCLUDE_PATH . "/index.php";
require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
Piwik_FrontController::getInstance()->init();
$request = new Piwik_API_Request('
method=Actions.getActions
&idSite=' . $idSite . '
&date=' . $date . '
&period=' . $period . '
&format=PHP
&filter_column=label
&filter_pattern=product.php
&filter_sort_column=nb_visits
&filter_sort_order=desc
&token_auth=anonymous
');
$result = $request->process();
// contains an array of visits to storefront.php
$result = unserialize($result);
$query = Piwik_Query("SELECT sp.product_id id, sp.name, sp.storefront_id sf_id, cl.company_name FROM sitedb.storefront_products sp INNER JOIN sitedb.storefronts sf ON sp.storefront_id = sf.id INNER JOIN sitedb.company_lookup cl ON sf.company_id = cl.id WHERE cl.id = {$company_id}");
$dataTable = new Piwik_DataTable();
while ($row = $query->fetch()) {
// piwik returns & escaped to & -- make sure that's what you use to search!
$this->array_search_in_level("/product.php?id=" . $row['id'] . "&sf_id=" . $row['sf_id'], $result, 'label', $storefront_array, 1);
if (is_array($storefront_array) && array_key_exists('nb_visits', $storefront_array)) {
$piwik_row = new Piwik_DataTable_Row;
$piwik_row->setColumns( array('id' => $row['id'], 'Product Name' => $row['name'], 'Page Views' => $storefront_array['nb_visits']) );
$dataTable->addRow($piwik_row);
}
}
return $dataTable;
}
However, the subTable never shows up. Am I doing something wrong?
Maybe you need to add the 'expanded=1' parameter to your API request?
http://piwik.org/docs/analytics-api/reference/#toc-optional-api-parameters
If you are looking for example code on how to use the piwik framework to plot custom data in plugins, it looks like they have a bit of doc: Piwik plugins docs