Last insert id return error in Yii - postgresql

I just executed some code in controller, and try to find the last inserted id.
But it display s error :
This is my code:
$sql = 'INSERT into "Tbl_Community" ("User_id","Community_name") VALUES (10,'new community')';
$connection = Yii::app() -> db;
$command = $connection -> createCommand($sql);
$command -> execute();
echo $connection->getLastInsertID();
The error:
[message:protected] => SQLSTATE[42602]: Invalid name: 7 ERROR: invalid name syntax
[string:Exception:private] =>
[code:protected] => 42602
[file:protected] => D:\wamp\www\Tiein\framework\db\CDbConnection.php
[line:protected] => 548
[trace:Exception:private] => Array
(
[0] => Array
(
[file] => D:\wamp\www\Tiein\framework\db\CDbConnection.php
[line] => 548
[function] => lastInsertId
[class] => PDO
[type] => ->
[args] => Array
(
[0] =>
)
)

with postgresql you can't get last by this way
$lastId= Yii::app()->db->getLastInsertID();
try this (tbl_user_group_id is your table id column and _seq is for postgresql)
$lastId = Yii::app()->db->getLastInsertID('tbl_user_group_id_seq');
OR
$lastId= Yii::app()->db->getCommandBuilder()->getLastInsertID('{{tablename}}') ;

Besides what user714965 pointed out, I usually put the parameters in execute just to make sure they are used properly by PDO. If you write SQL command like in your example and you read the parameters from a form it is problematic.
Yii::app()->db->createCommand('INSERT into "Tbl_Community" ("User_id","Community_name") VALUES (:User_id,:Community_name)')->execute(array(":User_id"=>10, ":Community_name"=>"new community"));
$id = Yii::app()->db->getLastInsertID();

Finally I got the solution :
$sql = 'INSERT into "Tbl_Community" ("User_id","Community_name") VALUES (10,\'new community\')';
$connection = Yii::app() -> db;
$command = $connection -> createCommand($sql);
$command -> execute();
$id = $connection->getCommandBuilder()->getLastInsertID('{{Tbl_Community}}');
echo $id;
PDO::lastInsertID() requires the name parameter when used with PDO_PGSQL so need to replace this code Yiii::app()->db->getLastInsertID(); by Yii::app()->db->getCommandBuilder()->getLastInsertID('{{tablename}}') ;
Refer this link

It may be too late to reply to this thread. But here is the case.
As Per the user 'Always Sunny' you can send the 'Sequence Name' by hardcoding, but that's not a good coding practice.
As per the user 'Kitchu' the use of 'getCommandBuilder' is good, because, provided the 'TableName', it will query the Schema and finds out the 'Sequence Name'. It will inturn query the CDBCommand's 'getLastInsertId' by passing the 'Sequence Name'
One thing to ensure that it, if you have not defined the 'Primary Key' on the table, then you will end up getting the value as 'NULL'

Related

Insert data with data type in laravel?

I am using laravel with mongodb, This is my update query
$user = User::where('_id', '=', $row)
->update(['userid' => $userid,
'username' => $username,
'email' => $emailid,
'mobileno' => $mobile,
'manager_mail' => $manager_mail,
'roleid' => $role]);
While inserting role id is inserted as a string, how can i insert as a integer? please help
If you know $roleid will always be a numeric value, you can use intval in php when passing $roleid.
E.g. intval($role)
Read about it here: http://php.net/manual/en/function.intval.php

How can I refine a REST query based on a linked module?

I'm trying to get all accounts that do not have an associated document.
This is what I have in mind:
$parameters = array(
'session' => $this->getSessionId(),
'module_name' => 'Accounts',
'query' => "accounts.id NOT IN (SELECT DISTINCT account_id FROM documents_accounts)",
);
but of course it doesn't work. I get an "Access denied" error (40).
Ideally I'd like to filter even further by querying for accounts that do not have an attached document of a given type. For example:
getAccountsWithout('contracts');
getAccountsWithout('quote1');
...
It could be that your are not correctly authenticating with the REST API. Or that your are not correctly provide what the method call needs.
If that is not the issue. One solution is to create a customer version the service/v4_1. So that you can add your own custom call.
This can be achieved by copying the v4_1 directory giving it a name like v4_1_1.
Rename the following:
SugarWebServiceImplv4_1.php to SugarWebServiceImplv4_1_1.php
SugarWebServiceUtilv4_1.php to SugarWebServiceImplv4_1_1.php
Change the class signatures to this:
SugarWebServiceImplv4_1:
class SugarWebServiceImplv4_1_1 extends SugarWebServiceImplv4_1
SugarWebServiceImplv4_1:
class SugarWebServiceUtilv4_1_1 extends SugarWebServiceUtilv4_1
Change the require/include paths in:
registry.php rest.php
soap.php
SugarWebServiceImplv4_1_1.php
SugarWebServiceImplv4_1_1.php
so that they now point to the 4_1_1 directory.
Implement a method in SugarWebServiceImplv4_1_1.php.
function get_without_documents($session, $module_name = 'accounts', $start = 1, $offset = 20) {
$output_list = array();
$db = DBManagerFactory::getInstance();
// just for example
$sql_query = "SELECT a.id FROM accounts a WHERE a.id NOT IN (SELECT DISTINCT account_id FROM documents_accounts)";
$result = $db->limitQuery($sql_query, $start, $offset,false);
while(($row = $db->fetchByAssoc($result)) != null){
$output_list[] = $row['id'];
}
return array(
'result_count'=> count($output_list),
'next_offset' => $offset + $start,
'entry_list' => $output_list,
);
}
Finally register the method and it the types in registry.php and the reference the url so that it uses v4_1_1.

Yii2-mongodb: How to catch mongodb insert returned mongo id

I would like to get the mongodb insert returned id for further insert specific operation my code is this:
$collection1 = $collection->insert(['username' => $this->email,
'password' =>sha1($this->input_password), 'full_name' => $this->full_name
'time_created' => '', 'time_updated' => '', 'time_last_visited' => '']);
when i does var_dump($collection1) function it shows me output
object(MongoId)#92 (1) { ["$id"]=> string(24) "54ba2b2c64363d640f000031" }
but when i try to access the id it shows me errors
i tried following options:
$insert_id = $collection1->primaryKey();
$insert_id = $collection1->getLastInsertID();
$id = $collection1->id;
$id = (string)$collection1['id'];
$id = $collection1['_id'];
but no options work. What is the right way?
Well i got my answer i tried another one differently & that works.
$id = (string) $collection1;
This returns me the string formatted mongoId.
$id = $collection->insert($data);

Zend framework group by

I'm trying to do a group by using Zend framework. Here's my code:
$table = new TableClass();
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
TableClass extends 'Zend_Db_Table_Abstract'.
I can see the query by looking at the mysql query log. The query is well formed - column1 is named in the query and the results look correct if I run the query in mysql workbench.
I cannot access the data in 'column1' - I always get this exception:
Uncaught exception 'Zend_Db_Table_Row_Exception' with message 'Specified column "column1" is not in the row'
I can however access the date column without issue.
I tried:
accessing the columns by array index:
$result[0]
but you get an exception (can't access the columns by index).
not using a column alias:
$select->from ("table", array("date", "sum(column1)"));
$column1 = $result["sum(column1)"];
but you get an exception (no such column "sum(column1)").
throwing in a Zend_Db_Expr:
"column1" => new Zend_Db_Expr ( "sum(column1)" )
but this doesn't help.
Some other examples I have seen suggest the use of the column names without aggregate functions, ie. "column1" instead of "sum(column1)" but that doesn't seem to me to be the answer - the query doesn't have any aggregate functions in it so mysql won't know what to do with it.
Any help appreciated.
Firstly, a quick tip for working with Zend_Db_Select (and by extension Zend_Db_Table_Select), you can view the generated SQL by invoking the toString method. It is vital to verify that your code generates the correct query before working with a result set:
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$sql = (string) $select; //Retrieve SQL as a string
Or simply
die($select); //print SQL
I wrote the following test script using your example and have no problems:
class Table extends Zend_Db_Table_Abstract
{
protected $_primary = 'id';
protected $_name = 'table';
}
$db = Zend_Db::factory('Pdo_Mysql', array(
'dbname' => 'test',
'username' => 'root',
'password' => '',
'host' => 'localhost'
));
$table = new Table($db);
$select = $table->select();
$select->from ($table, array("date", "column1" => new Zend_Db_Expr("sum(column1)")));
$select->group ( array ("date") );
$sql = (string) $select;
echo $sql;
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
echo '<br>' . $date . ': ' . $column1;
Use Zend_Debug::dump($result); to inspect data inside the Zend_Db_Table_Row if necessary.
In my case the SQL generated is as follows:
SELECT `table`.`date`, sum(column1) AS `column1` FROM `table` GROUP BY `date`

How do I go around this Zend_Form_Element_Select db error?

When i use the Zend_Form_Element_Select elements with multioptions i get this error when i pass the selected value to Zend_DB_Table to insert into the db
Message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'accounts_status ' in 'field list'
I have extracted some code snippets that i believe will go a long way into illustrating my problem.The accounts_status field DOES exist in my table
On my form construct have added the select element and options (I have left out the other elements)
$optionsstatus = array(
'active' => 'active',
'pending' => 'pending'
);
$optionsrole = array(
'guest' => 'guest',
'user' => 'user',
'writer' => 'writer',
'admin' => 'admin'
);
$status = new Zend_Form_Element_Select('accounts_status');
$status->setLabel('Status')
->setRequired(true)
->addMultiOptions($optionsstatus);
$role = new Zend_Form_Element_Select('accounts_role');
$role->setLabel('Role')
->setRequired(true)
->addMultiOptions($optionsrole);
I use the Zend_DB_table to insert the post values from my controller
public function addaccount($username, $fullname, $email,
$password,$status,$roles,$comments)
{
$data = array(
'accounts_username' => $username,
'accounts_fullname' => $fullname,
'accounts_email' => $email,
'accounts_password' => $password,
'accounts_status ' => $status,
'accounts_roles' => $roles,
'accounts_comments ' => $comments,
);
$this->insert($data);
}
In my controller i get the post values and send them to my model
$username = $form->getValue('accounts_username');
$fullname = $form->getValue('accounts_fullname');
$email = $form->getValue('accounts_email');
$password = $form->getValue('accounts_password');
$status = $form->getValue('accounts_status');
$roles = $form->getValue('accounts_roles');
$comments = $form->getValue('accounts_comments');
$accounts = new Model_DbTable_Account();
$accounts->addaccount($username, $fullname,$email,
$password,$status,$roles,$comments);
This approach works for me except when am dealing with the Zend_Form_Element_Select elements.Am just wondering if there is a specific way of dealing with this select elements when it comes to CRUD operations.
Message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'accounts_status ' in 'field list'
Maybe I'm crazy, but looks to me like there's an extra space on that end of that 'accounts_status ' field name.