How can I return the last inserted id in CodeIgniter 3? - codeigniter-3

Using CodeIgniter 3, I want to get the last auto-incremented id for the insert operation as the return value of my query but it is returning the wrong id greater than 0. Each time the record is inserted into the table, returned value is incremented by 1.
function insert($data)
{
$ip = $this->input->ip_address();
$this->db->set('application_date',date('Y-m-d H:i:s'));
$this->db->set('created_at', date('Y-m-d H:i:s'));
$this->db->set('created_ip',$ip);
$this->db->set('update_count', 1, FALSE);
$this->db->insert(TABLE_CUSTOMER, $this->security->xss_clean($data));
return $this->db->insert_id();
}

Related

How to insert empty array into jsonb column (pgsql) by Yii2?

Created a migration with a new field of jsonb type, not null and default value = []. (example of stored data: ["235", "214"]) and add a rule to model [['unique_users'], 'safe']
public function up()
{
$connection = Yii::$app->getDb();
$sql = 'ALTER TABLE offer ADD unique_users jsonb not null default \'[]\'';
$command = $connection->createCommand($sql, []);
$command->queryAll();
}
Result: Added a unique_users field with a default value [] to each row. jsonb_typeof(unique_users) returns an array type.
Created needed query for test
select jsonb_array_length(unique_users) from test where unique_users #> '"19"'::jsonb
Result from PgAdmin:
It seemed that everything was ready. But after saving a new record with Yii2, I received a query error:
ERROR: you can not get the length of a scalar
And I saw that another value was recorded in the field - ""
I was tryed to add the validation rule to Model: ['unique_users', 'default', 'value' => '[]'],.
Result:
...with the same problem of query - value is not an array. jsonb_typeof(unique_users) returns an string type.
How to insert empty array into jsonb column?
I think you're accidentally sending an empty string as the value for your unique_users field. If the value would be completely empty it should take the default DB value for the column. Please make sure the unique_users field is completely empty (null) when saving.
You can however also do this with a default value rule. This should do the trick:
['unique_users', 'default', 'value' => json_encode([])],
['unique_users', 'default', 'value' => []],

Date comparison in MongoDB Filter

I am trying to create a Filter that will that will return the rows where at least one minute has passed from the stored transactionDate. I am not getting an error but it is not returning any rows. The transactionDate is a timestamp in MongoDB and is stored as "transactionDate" : ISODate("2016-09-30T20:29:19.448Z")
Thanks! \m/ \m/
var filter = Builders<MyDocument>.Filter.Eq("Genre", "Rock");
filter = filter & (Builders<MyDocument>.Filter.Lt(x => x.transactionDate, DateTime.Now.AddSeconds(Math.Abs(60) * (-1))));
using (var cursor = await MyCollection.Find(filter)
.Sort(Builders<MyDocument>.Sort.Ascending(x => x.artist).Ascending(x => x.rating)).ToCursorAsync())
{
// foreach...
}
The above code actually does work. I had an issue in the data causing no results to be returned. \m/ \m/

Creating a SQLite table row updating row again and again

I have created a table for my application... first time user will give the input for two editText ,name and mobile number when table is empty after that only updating the first row of table...so on
A scenario:
add a new record with name:"name1", telephone: "123456789" --> new record
add a new record with name:"name2", telephone:"987654321" --> update the previously entered record.
If that what you want then:
be sure to always insert the new record with the same id as the previously inserted one.
use db.insertWithOnConflict()[ link ] to insert new records, passing the value CONFLICT_REPLACE [ link ] for the last parameter conflictAlgorithm
Sample Code
void Add_Contact(Person_Contact contact)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// SINGLE_ROW_ID is a constant holding the single row id that will be used. e.g: SINGLE_ROW_ID = 1
values.put( KEY_ID, SINGLE_ROW_ID );
values.put( KEY_NAME, contact.get_name() ); // Contact Name
values.put( KEY_PH_NO, contact.get_phone_number()); // Contact Phone
// Inserting Row
db.insert( TABLE_CONTACTS, null, values );
db.insertWithOnConflict( TABLE_CONTACTS,KEY_ID,values, SQLiteDatabase.CONFLICT_REPLACE );
db.close(); // Closing database connection
}

Entity query increments field value for every query (field is not autoincremented)

I have an entity query that when I run increments the value of my field. I am using entity framework and sql server 2012. Here is my query;
public void GetLastAccountNumber(ProductLine productLine, Action completed)
{
EntityQuery query = WASMDomainContext.GetContactCustomerAccountsQuery()
.Where(cca => cca.ProductLineId == productLine.Id)
.OrderBy(cca => cca.AccountNumber);
WASMDomainContext.Load(query, loadOp =>
{
Exception error = null;
ContactCustomerAccount lastAccount = null;
if (loadOp.HasError)
error = loadOp.Error;
else
lastAccount = loadOp.Entities.LastOrDefault();
// Invoke completion callback
completed(lastAccount, error);
}, null);
}
Query should return the last account number which is an integer field for now. However it returns an incremented value. For example in my table I have an accountnumber 0 the query returns an entity with account number as 1. My account number field is not auto increament and I find this very strange. And each time the above is called the AccountNumber field value increases by one but the database value will remain 0. I just want the query to return what is in my database. Any idea why this could be happening? Any help will be appreciated. Thank you all.

Cannot refresh row as parent is missing. Zend Framework

i am getting the error "Cannot refresh row as parent is missing" when I try to save. Here is my code
abstract class Webapp_Model_Resource_Db_Table_Abstract
extends Zend_Db_Table_Abstract
{
/**
* Save a row to the database
*
*
* #param array $info The data to insert/update
* #param Zend_DB_Table_Row $row Optional The row to use
* #return mixed The primary key
*/
public function saveRow($info, $row = null)
{
if (null === $row) {
$row = $this->createRow();
}
$columns = $this->info('cols');
foreach ($columns as $column) {
if (array_key_exists($column, $info)) {
$row->$column = $info[$column];
}
}
return $row->save();
}
}
when I call the saveRow() method, I pass in the $_POST values ($form->getValues())
I have reused this class with my other modules in the same application but now I am getting this error and I am not sure why. My table is pretty straight forward:
CREATE TABLE `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`headline` varchar(100) DEFAULT NULL,
`snippet` varchar(500) DEFAULT NULL,
`full_text` text,
`author` varchar(100) DEFAULT NULL,
`publish_from` date DEFAULT NULL COMMENT 'Publish date',
`publish_to` date DEFAULT NULL COMMENT 'Take it down or mark as draft after this date',
`datecreated` timestamp NULL DEFAULT NULL COMMENT 'First created on',
`revised` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp for the last time it was revised',
`draft` tinyint(1) DEFAULT '0' COMMENT 'Should not be published',
`departments_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=214 DEFAULT CHARSET=utf8 COMMENT='Stores news articles';
Anyone know what I am doing wrong?
::::::::::::::ADDTION:::::::::::::
public function saveNews($post,$defaults = array())
{
//get the form
$form = $this->getForm('article' . ucfirst($validator));
//validate
if(!$form->isValid($post)) {
return false;
}
//get fitered values
$data = $form->getValues();
//apply defaults
foreach($defaults as $col => $value) {
$data[$col] = $value;
}
//get the article if it exists
$article = array_key_exists('id', $data) ?
$this->getNewsById($data['id']) : null;
return $this->saveRow($data, $article);
}
When you pass an empty value for the primary key, Zend seems to return this value instead of the inserted auto-increment value - even though a new row is created properly with an auto-increment value, the inserted value will not be returned.
Maybe your problem is related to this. If so, try unsetting the id field prior to saving.
You have to tell DbTable that there is a Auto Incrementing Primary Key by setting $_sequence either to true or the Sequence Name.
15.5.4.1. Using a Table with an Auto-incrementing Key
Check your $info array. Probably you have some empty value for your primary key there.
So array_key_exists($column, $info) returns true and you assign an empty primary key to your row. And this causes the error as the row with this key does not exist.
try
if (array_key_exists($column, $info) and $column != 'YOUR_PRIMARY_KEY_NAME')
{
$row->$column = $info[$column];
}
In my case the problem was missing AUTO_INCREMENT.
Could you post the function:
$this->getNewsById($id)
There is your problem...