Novice: How to do update with id in cakephp2 mysql? - mysql

I'm new to cakephp2 and mysql and I want to create a mysql query to update the data with a id that has been passed in.I'm a very slow learner so I would want some help.
$this->User->updateAll(
array(
'User.checked_count' => '`User`.`checked_count` + 1',
'User.modified' => "'" . date('Y-m-d H:i:s') . "'"
),
array(
'User.username' => $username,
)
);
PS. How to get the results from the query above and use foreach loop? It doesn't work, so Im having a little trouble with it .

In cakePhp 2.x you can do it like that:
1) Below is simple update using save() function, where you pass id as reference and cake automatically updates the table when id is set else will insert the data in new row:
$this->User->id = $Id;
$this->User->save($this->request->data);
2) If you want one or more records in a single call to get updated use updateAll() function:
$this->User->updateAll(
array('User.checked_count' => $count),
array('User.id ' => $userId)
);

Try this code
$this->User->id = $passedId;
$this->User->save($this->data);
In above code If user_id is present then It update user data other wise it save userData.

Related

How to make multiple UPSERT in Yii2?

I am using Yii2 advance template. I have to insert 1000 to 2000 records in MySql Database.
Is it possible to make Multiple UPSERT Query in Yii2.
Please help me with your suggestion/answers. Thank you.
Since version 2.0.14 you have upsert() available.
Your code could look something like this:
$insertValues = [
'timestamp' => gmdate('YmdH'),
'entry_id' => $this->id,
'view_count' => 1,
];
$updateValues = ['view_count' => new \yii\db\Expression('table_name.view_count + 1')];
Yii::$app->db->createCommand()->upsert('table_name', $insertValues, $updateValues)->execute();
You can find the full documentation here: https://www.yiiframework.com/doc/api/2.0/yii-db-command#upsert()-detail
Try with modified batchInsert() method:
$db = \Yii::$app->db;
$sql = $db->queryBuilder->batchInsert($table, $fields, $rows);
$db->createCommand($sql . ' ON DUPLICATE KEY UPDATE')->execute();

YII SQL Query Optimization

I have a huge list of IDs that i need to query through a table to find if those IDs are available in the table, if yes fetch its model.
Since there are few thousands of IDs this process is really slow as I'm using CActiveRecord::find() mothod
ex. $book = Book::model()->find('book_id=:book_id', array(':book_id'=>$product->book_id));
I even indexed all possible keys, still no improvement.
Any suggestions to improve the execution speed?
thanks in advance :)
1)
Make a list of book ids
foreach $product in Product-List
$book_ids[$product->book_id] = $product->book_id;
Now query all Book models ( indexed by book_id )
$books = Book::model()->findAll(array(
'index' => 'book_id',
'condition' => 'book_id IN (' . implode(',', $book_ids). ')',
));
Integrate $books in your code, I believe you are looping through all products.
foreach $product in Product-List
if( isset($books[$product->book_id]) )
$model = $books[$product->book_id]
2) Another way (I am just assuming you have Product model)
in Product model add a relation to Book
public function relations() {
.......
'book'=>array(self::HAS_ONE, 'Book', 'book_id'),
.......
}
While retrieving your product list, add 'with' => array('book') condition, with any of CActiveDataProvider or CActiveRecord ...
//Example
$productList = Product::model()->findAll(array(
'with' => array('book'),
));
foreach( $productList as $product ) {
.......
if( $product->book != null )
$model = $product->book;
......
}
with either way you can reduce SQL queries.
Better if you use schema caching because Yii fetches schema each time we execute a query. It will improve your query performance.
You can enable schema caching by doing some configuration in config/main.php file.
return array(
......
'components'=>array(
......
'cache'=>array(
'class'=>'system.caching.CApcCache', // caching type APC cache
),
'db'=>array(
...........
'schemaCachingDuration'=>3600, // life time of schema caching
),
),
);
One more thing you can fetch specific column of the table that will improve performance also.
You can do it by using CDbCriteria with find method of CActiveRecord.
$criteria = new CDbCriteria;
$criteria->select = 'book_id';
$criteria->condition = 'book_id=:book_id';
$criteria->params = array(':book_id'=>$product->book_id);
$book = Book::model()->find($criteria);
I would suggest you to use any nosql database if you are processing thousands of records if that is suitable.

Codeigniter - How to get records from database where one fields value is more than another?

In my database I have two columns named 'amount_raised' and 'funding_goal'.
I would like to get all records from my database where the 'amount_raised' is equal to or more than the 'funding_goal'.
I am using Codeigniters active record. This is what I have so far:
function get_recently_successful($limit, $offset){
$data = '';
$this->db->order_by('date','desc');
$this->db->where('published', '1');
$this->db->where('amount_raised >=', 'funding_goal');
$query = $this->db->limit($limit, $offset)->get('projects');
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'date' => $row->date,
'project_title' => $row->project_title,
);
}
return $data;
}
The code above just returns all values in the database. Not how I specified it with where. How can I make it work??
Try this instead.
$this->db->where('amount_raised >= funding_goal');
Right now you send the value 'funding_goal' through the query, thus making it:
WHERE amount_raised >= 'funding_goal'
You want it compare with a column and not a string:
WHERE amount_raised >= funding_goal
You can always troubleshoot your query by inserting:
echo $this->db->last_query();
After the $query = row.
If you are using multiple condition in array, you can try the below as well:
$this->db->where(array('status' => 'Active', 'category' => $catId));
You can use another condition as well like this:
$this->db->where('amount_raised >= funding_goal');
You can use the last_query() to see the sql query as well to understand it.

Filtering theme_table in Drupal

I just created a data table based on a query and displayed it successfully using theme_table().
Now, I'd like to add some filters to the table but have no idea how to proceed.
Is there a built-in feature that allow me to do this easily, or should I manually add a form and update the query/redisplay the results each time the user selects something?
Thanks for your help!
I think you want to use pager_query and tablesort_sql: it's especially made for creating tables of data with pagination and sorting capabilities (and themes usually theme such tables nicely out of the box).
Example:
<?php
// The regular query without sorting or pagination parameters
$sql = 'SELECT cid, first_name, last_name, company, city FROM {clients}';
// Number of rows per page
$limit = 20;
// List of table columns ("field" is the matching database column from the sql query)
$header = array(
array('data' => t('Name'), 'field' => 'last_name', 'sort' => 'asc'),
array('data' => t('Company'), 'field' => 'company'),
array('data' => t('City'), 'field' => 'city')
);
// Calculates how to modify the SQL query according to the current pagination and sorting settings
// Then performs the database query
$tablesort = tablesort_sql($header);
$result = pager_query($sql . $tablesort, $limit);
$rows = array();
while ($client = db_fetch_object($result)) {
$rows[] = array(l($client->last_name.', '.$client->first_name, 'client/'.$client->cid), $client->company, $client->city);
}
// A message in case no results were found
if (!$rows) {
$rows[] = array(array('data' => t('No client accounts created yet.'), 'colspan' => 3));
}
// Then you can pass the data to the theme functions
$output .= theme('table', $header, $rows);
$output .= theme('pager', NULL, $limit, 0);
// And return the HTML output
print $output;
?>
(I added comments, but the original version of the example comes from this page)
Alternatively, maybe you don't need to make a module at all if you're just trying to make a page that displays a list of data, you may prefer using the Views module.

Insert a time + n in mySQL using Zend_db_table!

$data = array (
'next' => "NOW() + 5",
'interval' => $dom["USER"][0]["STATUSES_COUNT"][0]["data"],
'good' => $good,
'tries' => $p->tries + 1
);
$where = $service->getAdapter()->quoteInto('id = ?', $p->id);
$service->update($data, $where);
to insert something to a database using PHP on zend and mySQL.
The "next" => "NOW()" wont work. I could put the CURRENT_TIMESTAMP as default value, but what i actually want is to insert the timestamp refering this moment, plus some time.
I could rewrite some parts of the program to use pure php dates(instade of pure mySQL dates). Dont know what is best, or what should i do. Do you know how i could make this update work with mySQL doing the timing?
I solved it with the next statement, very usefull:
'next' => new Zend_Db_Expr('TIMESTAMPADD(MINUTE,1,NOW())'),