Codeigniter Active record query - sql

How can I write this procedural query as codeigniter active record query (update_batch mode )
UPDATE products SET current_stock = current_stock + 1 where product_id = 1

You can use update_batch like this:
$products = $this->db->get('products'))->result();
for( $i = 0; $i < count($products); $i++){
$data[] = array(
'product_id' => $product[$i]->product_id,
'current_stock' => $product[$i]->current_stock + 1
);
}
$this->db->update_batch('products', $data, 'product_id');

You can use below query as explained on Codeigniter Query Builder Class:
$this->db->set('current_stock', 'current_stock+1', FALSE);
$this->db->where('product_id', 2);
$result = $this->db->update('products');

Related

Wordpress $wpdb->update not working correct in for loop

Wordpress $wpdb->update() function is not executing the sql. I tried hard coded the values, it worked but not working in loop.
Here is my code:
for ($i=0; $i < count($excelData); $i++) {
$product = $excelData[$i];
$product_id = $product['item_id'];
$product_price = $product['item_price'];
// $sqlStrings[] = "UPDATE $branch SET price = $product_price WHERE details_id = $product_id";
$wpdb->update(
$branch,
array(
'price' => $product_price,
),
array(
'details_id' => $product_id,
),
);
}
Loop is repeating self 140 times.

Get database records in TYPO3 viewHelper

I want to create a database query in a view helper, this works with the following code:
$uid = 11;
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_test_domain_model_author');
$query = $queryBuilder
->select('*')
->addSelectLiteral(
$queryBuilder->expr()->count('tx_test_domain_model_author.author', 'counter')
)
->from('tx_test_domain_model_author')
->join(
'tx_test_domain_model_author',
'tx_test_publication_author_mm',
'tx_test_publication_author_mm',
$queryBuilder->expr()->eq(
'tx_test_domain_model_author.uid',
$queryBuilder->quoteIdentifier('tx_test_publication_author_mm.uid_foreign')
)
)
->where(
$queryBuilder->expr()->eq(
'tx_test_publication_author_mm.uid_local',
$queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
)
)
->orderBy('tx_test_domain_model_author.uid', 'ASC');
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
print_r($res);
However, I only get one record, although the counter tells me it would be 3.
What am I doing wrong?
If the counter says its three items, then try change this:
$result = $query->execute();
$res = [];
while ($row = $result->fetch()) {
$res[] = $row;
}
into this:
$result = $query->execute()->fetchAll();
That fetches all rows into an array that you walk throug with:
foreach($result as $row){
...
}
It seems the QueryBuilder works differently, this gives me one result namely the first entry in the table:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_test_publication_author_mm');
$query = $queryBuilder
->select('*')
->from('tx_test_publication_author_mm');
$result = $query->execute()->fetchAll();
foreach($result as $row){
echo $row['field'];;
}
This gives me all results:
$db = mysqli_connect($dbHost, $dbUser, $dbPassword, $dbName) or die (mysql_error ());
$sql = "SELECT * FROM tx_test_publication_author_mm";
foreach ($db->query($sql) as $row) {
echo $row['field'];
}

I need to fix with code igniter query

I am trying to get details from table1 and table2 on basis of table3 id array.
table3 id and table1 ids are availale in table2.
// $ids is a array of ids like: Array ( [ids] => 10,11 )
function get_detail($ids) {
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.aID = table2.aID');
$this->db->join('table3', 'table2.bID = table3.bID','left');
$this->db->where('table3.bID', $ids);
$query = $this->db->get();
}
When you have multiple values you should use IN
Replace
$this->db->where();
With
$this->db->where_in();
Both takes (col, value);
Note : // $ids = Array ( 10,11 );
Hello you use where_in like this
function get_detail($ids) {
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.aID = table2.aID');
$this->db->join('table3', 'table2.bID = table3.bID','left');
$this->db->where_in('table3.bID', $ids);
$query = $this->db->get();
}
Note : Pass $ids in array format
$ids = Array (10,11);
you can use an array
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);

how to get `dataProvider ` with each product_id

i have order table where in product_id is string Like 10,11,12,13. And have Product table with this id.
how to get dataProvider with each product_id
My code is
public function getProducts($id){
$idarray = explode(',', $id);
$dataProviderProduct = Array();
foreach($idarray as $i=>$id){
$dataProviderProduct[$i]=new CActiveDataProvider('Product',
array( 'criteria'=>array(
'condition'=>'id=:id',
'params'=>array(':id' => $id),
),
'pagination'=>array( 'pageSize'=>10),
)
);
}
return $dataProviderProduct;
}
But this is wrong code
Use addInCondition like this:
$idarray = explode(',', $id);
$criteria = new CDbCriteria();
$criteria->addInCondition('id', $idarray);
$data = ModelName::model()->findAll($criteria);

Custom post type yearly/ monthly archive

I have a custom post type "news" in my Wordpress site. I am using Advanced Custom Fields plugin to add meta data to each post.
I want to create an array of news items as an archive:
[2013]
[January] => 5
[2012]
[January] => 20
[February] => 10
[2011]
[April] => 30
I managed to get this working using:
global $wpdb;
$news = $wpdb->get_results(
"SELECT wp_posts.post_date, COUNT(wp_posts.ID) as count
FROM $wpdb->posts
WHERE
wp_posts.post_type = 'news' AND
wp_posts.post_status = 'publish' AND
wp_posts.post_date <= CURDATE() AND
wp_posts.post_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR)
GROUP BY YEAR(wp_posts.post_date), MONTH(wp_posts.post_date)
ORDER BY wp_posts.post_date DESC",
ARRAY_A);
$archive = array();
foreach ($news as $post):
$year = date('Y', strtotime($post['post_date']));
$month = date('m', strtotime($post['post_date']));
$month_name = date('F', strtotime($post['post_date']));
$post['url'] = 'NOT SURE ABOUT URL';
$archive[$year][$month_name] = $post;
endforeach;
I need to be able to link to specific years and months using http://example.com/2012/ and http://example.com/2012/10/.
As this involves a custom post type "news" I'm unsure how to make this happen?
In order to do what you require, you need to modify Wordpress rewrites to be able to capture the year/month/etc post data for a custom post type.
You may do this with the following code:
/**
* Custom post type date archives
*/
/**
* Custom post type specific rewrite rules
* #return wp_rewrite Rewrite rules handled by Wordpress
*/
function cpt_rewrite_rules($wp_rewrite) {
$rules = cpt_generate_date_archives('news', $wp_rewrite);
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
return $wp_rewrite;
}
add_action('generate_rewrite_rules', 'cpt_rewrite_rules');
/**
* Generate date archive rewrite rules for a given custom post type
* #param string $cpt slug of the custom post type
* #return rules returns a set of rewrite rules for Wordpress to handle
*/
function cpt_generate_date_archives($cpt, $wp_rewrite) {
$rules = array();
$post_type = get_post_type_object($cpt);
$slug_archive = $post_type->has_archive;
if ($slug_archive === false) return $rules;
if ($slug_archive === true) {
$slug_archive = $post_type->name;
}
$dates = array(
array(
'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
'vars' => array('year', 'monthnum', 'day')),
array(
'rule' => "([0-9]{4})/([0-9]{1,2})",
'vars' => array('year', 'monthnum')),
array(
'rule' => "([0-9]{4})",
'vars' => array('year'))
);
foreach ($dates as $data) {
$query = 'index.php?post_type='.$cpt;
$rule = $slug_archive.'/'.$data['rule'];
$i = 1;
foreach ($data['vars'] as $var) {
$query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
$i++;
}
$rules[$rule."/?$"] = $query;
$rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
$rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
$rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
}
return $rules;
}
You will notice that I have hard-coded news in to the $rules = cpt_generate_date_archives('news', $wp_rewrite); portion of the code. You can change this as needed.
With this code, you should be able to navigate to http://yoursite.com/news/2013/02/ and receive an archive listing for that specific post type for that specific time.
For completeness, I will include how to generate a monthly archive widget in order to utilize this.
/**
* Get a montlhy archive list for a custom post type
* #param string $cpt Slug of the custom post type
* #param boolean $echo Whether to echo the output
* #return array Return the output as an array to be parsed on the template level
*/
function get_cpt_archives( $cpt, $echo = false )
{
global $wpdb;
$sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' GROUP BY YEAR($wpdb->posts.post_date), MONTH($wpdb->posts.post_date) ORDER BY $wpdb->posts.post_date DESC", $cpt);
$results = $wpdb->get_results($sql);
if ( $results )
{
$archive = array();
foreach ($results as $r)
{
$year = date('Y', strtotime( $r->post_date ) );
$month = date('F', strtotime( $r->post_date ) );
$month_num = date('m', strtotime( $r->post_date ) );
$link = get_bloginfo('siteurl') . '/' . $cpt . '/' . $year . '/' . $month_num;
$this_archive = array( 'month' => $month, 'year' => $year, 'link' => $link );
array_push( $archive, $this_archive );
}
if( !$echo )
return $archive;
foreach( $archive as $a )
{
echo '<li>' . $a['month'] . ' ' . $a['year'] . '</li>';
}
}
return false;
}
To use this function just supply the slug of the custom post type, ie: get_cpt_archives( 'news' ). This will return an array of unique Year/Dates/Links, ie:
Array
(
[0] => Array
(
[month] => February
[year] => 2013
[link] => http://yoursite.com/news/2013/02
)
[1] => Array
(
[month] => January
[year] => 2013
[link] => http://yoursite.com/news/2013/01
)
)
You can loop through these with a foreach and output them however you want.
Alternatively, you can use get_cpt_archives( 'news', true ) which will automatically echo each item wrapped in an <li> linking to its specific archive.
The formatting of the output is not exactly what you wanted, so you will have to tweak it a bit to get it to display in the
Year
Month
Month
Year
Month
format that you require.
I hope this helps.
I know this is an old post, but there is a much more succinct way of doing what the OP is asking:
function cpt_add_rewrite_rules()
{
$cpt = 'news';
add_rewrite_rule($cpt.'/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})?$',
'index.php?post_type='.$cpt.'&year=$matches[1]&monthnum=$matches[2]&day=$matches[3]',
'top');
add_rewrite_rule($cpt.'/([0-9]{4})/([0-9]{1,2})?$',
'index.php?post_type='.$cpt.'&year=$matches[1]&monthnum=$matches[2]',
'top');
add_rewrite_rule($cpt.'/([0-9]{4})?$',
'index.php?post_type='.$cpt.'&year=$matches[1]',
'top');
}
add_filter('init', 'cpt_add_rewrite_rules');