Codeigniter query with alias and number as column - codeigniter

I would like to replace column name with numbers in codeigniter
It does work well with letters but not with numbers
$this->db->select ('Observation.id_observation as 1');
$this->db->from ( 'Observation' );
$this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
Observation.id_observation' , 'left' );
$this->db->where('Observation.id_parcelle', $id_parcelle);
$this->db->where('Observation.id_observateur', $user_id);
$this->db->where('Observation.date_observation >=', $date_start);
$this->db->where('Observation.date_observation <=', $date_end);
return $this->db->get()->result();

Try the following
$this->db->select ('Observation.id_observation as `1`');
This will generate query as
Select `observation` as `1`....
From the Docs
Identifiers may begin with a digit but unless quoted may not consist solely of digits.

You can set alias name as string so you need to give within single quotes otherwise you will get syntax error
$this->db->select ('Observation.id_observation as `1`',FALSE);
$this->db->from ( 'Observation' );
$this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
Observation.id_observation' , 'left' );
$this->db->where('Observation.id_parcelle', $id_parcelle);
$this->db->where('Observation.id_observateur', $user_id);
$this->db->where('Observation.date_observation >=', $date_start);
$this->db->where('Observation.date_observation <=', $date_end);
return $this->db->get()->result();
OR
$var = '1';
$this->db->select ('Observation.id_observation as `'.$var.'`',FALSE);
OR
$query=$this->db->query('SELECT Observation.id_observation as "1" FROM Observation LEFT JOIN Enregistrement ON Enregistrement.id_observation =
Observation.id_observation WHERE Observation.id_parcelle = '.$id_parcelle.' AND Observation.id_observateur = '.$user_id.' AND Observation.date_observation >= "'.$date_start.'" AND Observation.date_observation <= "'.$date_end.'" ');
return $query->result();

You can try this:
$this->db->select ("Observation.id_observation as '1'");
Hope It will work.

This is what i had to do in the controller ! I very don't like this solultion but it does work:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT
Observation.id_observation as '0',
Observation.checkseries as '1'
FROM Observation
LEFT JOIN Enregistrement ON Enregistrement.id_observation = Observation.id_observation
WHERE
Observation.id_parcelle = '$parcellecultures->id_parcelle'
AND Observation.id_observateur = '$user'
AND Observation.date_observation >= '$date_start'
AND Observation.date_observation <= '$date_end'
";
//echo $sql;
$result = $conn->query($sql);
//print_r($result);exit;
$conn->close();
I still look for another solution ....

Related

how to retrieve different names from same table with different ids on join laravel

I need to get names from destinations table for each from_destination_id and to_destination_id
as fromDestinationName and toDestinationName
$bookingTransfersData = DB::table('transfers as t')
->select('t.periodStart as periodStart', 't.periodEnd as periodEnd','t.days','t.transfer_id','t.cost_round_trip',
't.cost_one_way','t.status','d.destination_id as destinationId','d.name as destinationName', 't.type',
'tf.name as officeName', 'ag.name as agencyName', 'u.name as userName', 'v.name as vehicleName')
->join('destinations as d', function ($join){
$join->on('t.from_destination_id','=','d.destination_id')
->orOn('t.to_destination_id','=','d.destination_id');
})->join('vehicles as v','t.vehicle_id','=','v.vehicle_id')
->join('transfer_offices as tf','t.office_id','=','tf.transfer_office_id')
->join('agencies as ag','t.forAgency_id','=','ag.agency_id')
->join('users as u','t.addedBy_user_id','=','u.id')
->get();
i want to get the names of each id after this results
$searchResults = $bookingTransfersData
->where('periodStart','between', $periodStart && $periodEnd)
->where('periodEnd','between', $periodStart && $periodEnd)
->where('destinationName','=',$from_destination_name && $to_destination_name)->where('type','like', $type);
like:
$fromDestinationName = $searchResults->pluck('from_destination_id','destinationName')
->where('from_destination_id','=','destinationId');
but $fromDestinationName return an empty collection
please help :)
I solved it by removing this join:
->join('destinations as d', function ($join){
$join->on('t.from_destination_id','=','d.destination_id')
->orOn('t.to_destination_id','=','d.destination_id');
})
and add for each destionation_id a join to retrive each name
and this will not work if I don't add for table name that i joined two times as to name it new name like
'destinations as d1' and 'destinations as d2'
$bookingTransfersData = DB::table('transfers as t')
->select('t.periodStart as periodStart', 't.periodEnd as periodEnd','t.days','t.transfer_id','t.cost_round_trip',
't.cost_one_way','t.status','d1.destination_id as fromDestinationId','d1.name as fromDestinationName', 't.type',
't.to_destination_id','tf.name as officeName', 'ag.name as agencyName', 'u.name as userName', 'v.name as vehicleName',
't.from_destination_id', 'd2.destination_id as toDestinationId','d2.name as toDestinationName')
->join('destinations as d1','t.from_destination_id','=','d1.destination_id')
->join('destinations as d2','t.to_destination_id','=','d2.destination_id')
->join('vehicles as v','t.vehicle_id','=','v.vehicle_id')
->join('transfer_offices as tf','t.office_id','=','tf.transfer_office_id')
->join('agencies as ag','t.forAgency_id','=','ag.agency_id')
->join('users as u','t.addedBy_user_id','=','u.id')->get();
the problem solved :)

Doctrin's Query Builder. Query with AND in where clause

I have a query in Query Builder in Doctrine. My query is:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1')
->getQuery();
How Could I get query with AND clause? I mean to replace cc.active = 1 AND system_category=1' instead cc.active = 1 in where clause.
I'm trying in that way:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1 AND system_category=1')
->getQuery();
But in that way it's dosen't work. How could I do that correctly?
I would be greateful for help.
Best regards
try this:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1')
->andWhere('system_category=1')
->getQuery();
I suggest to you to use parameters like this:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = :active')
->andWhere('system_category=:system_category')
->setParameters(
[
'active' => 1,
'system_category' => 1
]
)
->getQuery();

Catalog Price Rules applied to special_price

First question on stackoverflow...i am excited :)
Currently magento is using the special price if its lower than the applied catalog price rule. If the catalog price rule makes the product cheaper than the special price, then the catalog price rule defines the shop price.
I am looking for an elegant way to make catalog price rules be applied
to the special price (additionally). Maybe there is some store config for it? Maybe
there is some neat observer way?
Thank you so much!
Works up to current Magento 1.9.3.10. Just tested it in a project after update. Josef tried another approach which might work as well.
I am sad to say, I solved my first real stackoverflow question for my own:
Goto Mage_CatalogRule_Model_Resource_Rule
Goto method _getRuleProductsStmt
Add this to the initial select of the method before the first original ->from:
$select->from(null, array('default_price' => new Zend_Db_Expr("CASE
WHEN pp_default_special.value THEN pp_default_special.value ELSE
pp_default_normal.value END")));
Add this after the first join() has happened
$specialPriceAttr = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'special_price');
$specialPriceTable = $specialPriceAttr->getBackend()->getTable();
$specialPriceAttributeId= $specialPriceAttr->getId();
$joinCondition2 = '%1$s.entity_id=rp.product_id AND (%1$s.attribute_id=' . $specialPriceAttributeId . ')
AND %1$s.store_id=%2$s';
$select->join(
array('pp_default_special'=>$specialPriceTable),
sprintf($joinCondition2, 'pp_default_special', Mage_Core_Model_App::ADMIN_STORE_ID), null
);
How it works:
When a catalog price rule is applied (via backend or cron) the db table catalogrule_product_price is populated. The above SQL magic joins the special_price (if exists) to the resultset as column default_value, if no special_price is found the regular price gets joined.
The result has been checked and is working.
Have fun! And dont hack the core!
There seem to be some changes in newer Magento releases!
For 1.9 i had to:
copy app/code/core/Mage/CatalogRule/Model/Action/Index/Refresh.php to app/code/local/Mage/CatalogRule/Model/Action/Index/Refresh.php
Change _prepareTemporarySelect.
I post the function in full here. Joins for special_price are added and then the price added to the selection of the price field. It still prefers group prices, becuas I never use them, but that can be changed easily!
protected
function _prepareTemporarySelect(Mage_Core_Model_Website $website)
{
/** #var $catalogFlatHelper Mage_Catalog_Helper_Product_Flat */
$catalogFlatHelper = $this->_factory->getHelper('catalog/product_flat');
/** #var $eavConfig Mage_Eav_Model_Config */
$eavConfig = $this->_factory->getSingleton('eav/config');
$priceAttribute = $eavConfig->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'price');
$specialPriceAttr = Mage::getSingleton('eav/config')->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'special_price');
$specialPriceTable = $specialPriceAttr->getBackend()->getTable();
$specialPriceAttributeId = $specialPriceAttr->getId();
$select = $this->_connection->select()->from(array(
'rp' => $this->_resource->getTable('catalogrule/rule_product')
) , array())->joinInner(array(
'r' => $this->_resource->getTable('catalogrule/rule')
) , 'r.rule_id = rp.rule_id', array())->where('rp.website_id = ?', $website->getId())->order(array(
'rp.product_id',
'rp.customer_group_id',
'rp.sort_order',
'rp.rule_product_id'
))->joinLeft(array(
'pg' => $this->_resource->getTable('catalog/product_attribute_group_price')
) , 'pg.entity_id = rp.product_id AND pg.customer_group_id = rp.customer_group_id' . ' AND pg.website_id = rp.website_id', array())->joinLeft(array(
'pgd' => $this->_resource->getTable('catalog/product_attribute_group_price')
) , 'pgd.entity_id = rp.product_id AND pgd.customer_group_id = rp.customer_group_id' . ' AND pgd.website_id = 0', array());
$storeId = $website->getDefaultStore()->getId();
if ($catalogFlatHelper->isEnabled() && $storeId && $catalogFlatHelper->isBuilt($storeId))
{
$select->joinInner(array(
'p' => $this->_resource->getTable('catalog/product_flat') . '_' . $storeId
) , 'p.entity_id = rp.product_id', array());
$priceColumn = $this->_connection->getIfNullSql($this->_connection->getIfNullSql('pg.value', 'pgd.value') , $this->_connection->getIfNullSql('p.special_price', 'p.price'));
}
else
{
$select->joinInner(array(
'pd' => $this->_resource->getTable(array(
'catalog/product',
$priceAttribute->getBackendType()
))
) , 'pd.entity_id = rp.product_id AND pd.store_id = 0 AND pd.attribute_id = ' . $priceAttribute->getId() , array())->joinLeft(array(
'pspd' => $specialPriceTable
) , 'pspd.entity_id = rp.product_id AND (pspd.attribute_id=' . $specialPriceAttributeId . ')' . 'AND pspd.store_id = 0', array())->joinLeft(array(
'p' => $this->_resource->getTable(array(
'catalog/product',
$priceAttribute->getBackendType()
))
) , 'p.entity_id = rp.product_id AND p.store_id = ' . $storeId . ' AND p.attribute_id = pd.attribute_id', array())->joinLeft(array(
'psp' => $specialPriceTable
) , 'psp.entity_id = rp.product_id AND (psp.attribute_id=' . $specialPriceAttributeId . ')' . 'AND psp.store_id = ' . $storeId, array());
$priceColumn = $this->_connection->getIfNullSql($this->_connection->getIfNullSql('pg.value', 'pgd.value') , $this->_connection->getIfNullSql('psp.value', $this->_connection->getIfNullSql('pspd.value', $this->_connection->getIfNullSql('p.value', 'pd.value'))));
}
$select->columns(array(
'grouped_id' => $this->_connection->getConcatSql(array(
'rp.product_id',
'rp.customer_group_id'
) , '-') ,
'product_id' => 'rp.product_id',
'customer_group_id' => 'rp.customer_group_id',
'from_date' => 'r.from_date',
'to_date' => 'r.to_date',
'action_amount' => 'rp.action_amount',
'action_operator' => 'rp.action_operator',
'action_stop' => 'rp.action_stop',
'sort_order' => 'rp.sort_order',
'price' => $priceColumn,
'rule_product_id' => 'rp.rule_product_id',
'from_time' => 'rp.from_time',
'to_time' => 'rp.to_time'
));
return $select;
}
I fixed it in another way. It was just easy to put into the price field for example 100 and then into special price field 90 when there was 10% discount on product page but now I removed special price from product page and just created catalog price rule 10% discount to that product(s) and now other rules also work:)

Codeigniter CSV upload then explode

I have some code that uploads the CSV file to the specified folder, but it doesn't update the database.
public function do_upload()
{
$csv_path = realpath(APPPATH . '/../assets/uploads/CSV/');
$config['upload_path'] = $csv_path;
$config['allowed_types'] = '*'; // All types of files allowed
$config['overwrite'] = true; // Overwrites the existing file
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->layout->buffer('content', 'program/upload', $error);
$this->layout->render();
}
else
{
$image_data = $this->upload->data();
$fname = $image_data['file_name'];
$fpath = $image_data['file_path'].$fname;
$fh = fopen($fpath, "r");
$insert_str = 'INSERT INTO wc_program (JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish) VALUES '."\n";
if ($fh) {
// Create each set of values.
while (($csv_row = fgetcsv($fh, 2000, ',')) !== false) {
foreach ($csv_row as &$row) {
$row = strtr($row, array("'" => "\'", '"' => '\"'));
}
$insert_str .= '("'
// Implode the array and fix pesky apostrophes.
.implode('","', $csv_row)
.'"),'."\n";
}
// Remove the trailing comma.
$insert_str = rtrim($insert_str, ",\n");
// Insert all of the values at once.
$this->db->set($insert_str);
echo '<script type="text/javascript">
alert("Document successfully uploaded and saved to the database.");
location = "program/index";
</script>';
}
else {
echo '<script type="text/javascript">
alert("Sorry! Something went wrong please proceed to try again.");
location = "program/upload";
</script>';
}
}
}
When I run var_dump($fh); it shows: resource(89) of type (stream)
When I run var_dump($fpath) it shows: string(66) "/Applications/MAMP/htdocs/site/assets/uploads/CSV/wc_program.csv"
So it all uploads but what is wrong with it not updating the database?
I have tried all kinds of changing the fopen method but still no joy, I really need it to add to the database and the insert query and set query should do the trick but it doesn't.
Any help greatly appreciated!
You are not running any query on the database. You are mixing active record syntax with simple query syntax. The active record insert query will be executed by calling.
$this->db->insert('my_table');
db::set() does not actually query the database. It takes in a key/value pair that will be inserted or updated after db::insert() or db::update() is called. If you build the query yourself you need to use the db::query() function.
Review the active directory documentation.
You can use $this->db->query('put your query here'), but you lose the benefit of CodeIgniter's built in security. Review CodeIgniter's query functions.
I'll give you examples of just a few of the many ways you can insert into a database using CodeIgniter. The examples will generate the query from your comment. You will need to adjust your code accordingly.
EXAMPLE 1:
$result = $this->db
->set('JobRef', 911847)
->set('Area', 'Coastal')
->set('Parish', 'Yapton')
->set('AbbrWorkType', 'Micro')
->set('WorkType', 'Micro-Asphalt Surfacing')
->set('Timing', 'TBC')
->set('TrafficManagement', 'No Positive Traffic Management')
->set('Location', 'Canal Road (added PMI 16/07/12)')
->set('Duration', '2 days')
->set('Start', '0000-00-00')
->set('Finish', '0000-00-00')
->insert('wc_program');
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n\n";
print_r($result);
EXAMPLE 2 (Using an associative array):
$row = array(
'JobRef' => 911847,
'Area' => 'Coastal',
'Parish' => 'Yapton',
'AbbrWorkType' => 'Micro',
'WorkType' => 'Micro-Asphalt Surfacing',
'Timing' => 'TBC',
'TrafficManagement' => 'No Positive Traffic Management',
'Location' => 'Canal Road (added PMI 16/07/12)',
'Duration' => '2 days',
'Start' => '0000-00-00',
'Finish' => '0000-00-00'
);
$this->db->insert('wc_program', $row);
// This will do the same thing
// $this->db->set($row);
// $this->db->insert('wc_program');
echo $this->db->last_query();
Example 1 and 2 are using the Active Record. The information is stored piece by piece and then the query is built when you make the final call. This has several advantages. It allows you to build queries dynamically without worrying about SQL syntax and order of the keywords. It also escapes your data.
EXAMPLE 3 (Simple Query):
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
("911847","Coastal","Yapton","Micro","Micro-Asphalt Surfacing","TBC","No Positive Traffic Management","Canal Road (added PMI 16/07/12)","2 days","0000-00-00","0000-00-00")';
$result = $this->db->query($query);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
This way leaves all the protection against injection up to you, can lead to more errors, and is harder to change/maintain.
If you are going to do it this way you should use the following syntax, which will protect against injection.
EXAMPLE 4:
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);';
$row = array(
911847,
'Coastal',
'Yapton',
'Micro',
'Micro-Asphalt Surfacing',
'TBC',
'No Positive Traffic Management',
'Canal Road (added PMI 16/07/12)',
'2 days',
'0000-00-00',
'0000-00-00'
);
$result = $this->db->query($query, $row);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
CodeIgniter will replace each "?" in the query with the corresponding value from the array after it is escaped. You can use this to run many queries that are of the same form, but have different data just by updating the $row array and benefit from CI's built in security.

Codeigniter - brackets with activerecord?

How to have round brackets symbol in Codeigniter's active record SQL queries?
e.g. how to accomplish
SELECT * FROM `shops` WHERE (`shopid` = '10' OR `shopid` = '11') AND `shopid` <> '18'
$where="(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where, NULL, FALSE);
and for the AND condition use
$this->db->where('shopid <>', '18')
ie
$where="(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where, NULL, FALSE);
$this->db->where('shopid <>', '18')
I think you could do something like:
$where = "(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where) // or statement here
->where('shopid <>', '18') // chaining with AND
->get('shops');
Not entirely sure about the syntax, I'm writing this off the top of my head. I'll take a look at it when I get home if this doesn't work.
You can just do something like:
$this->db->select('field')->from('shops')->where("(`shopid` = '10' OR `shopid` = '11'")->where("`shopid` <> '18'");
$query = $this->db->get();
You can write your own clauses
manually:
$where = "name='Joe' AND status='boss'
OR status='active'";
$this->db->where($where);
Source: http://www.codeignitor.com/user_guide/database/active_record.html#where
$this->db->select()
->from('shops')
->where("'(`shopid` = '10' OR `shopid` = '11')")
->where('shopid !=', 18);
$this->db->get()->result();

Resources