unable delete all selected checkbox rows in yii2 - yii2-advanced-app

can anybody explain me how to delete only selected row or all selected row by checkbox it have below code but giving me error sql exception Exception (Database Exception) 'yii\db\Exception' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
The SQL being executed was: DELETE FROM usermaster WHERE id='28''
public function actionMultipledelete() {
if (\Yii::$app->request->post()) {
$keys=array();
$keys = \Yii::$app->request->post('id'); // id is array
}
UsermasterModel::deleteAll(['IN','id',$keys]);
return $this->redirect(['index']);
}

Simply use this
$keys = implode(',', $array);
$connection = Yii::$app->db; $command =
$connection->createCommand("DELETE FROM usermaster where id IN
(".$keys.")");

Related

primary key ID gives me repeated " 0 " value with android app

I try to make contactsApp with android , when I debug it the primary key repeat its value which is zero
AND HERE IS THE SQLiteOpenHelper class :
// get all Contacts
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
// HERE is where the error come...
try{
if (cursor.getString(0) != null)
contact.setId(Integer.parseInt(cursor.getString(0)));
}catch (Exception e){e.printStackTrace();}
contact.setName(cursor.getString(1) );
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
at first the error was NonNullException at this line
contact.setId(Integer.parseInt(cursor.getString(0)));
so I surround it with try catch then the app debug correctly but still gives wrong value for the INTEGER PRIMARY KEY id
the final result should be like
ID: 1, Name 1 , 111111111
ID: 2, Name 2 , 22222222
ID: 3, Name 3 , 33333333
ID: 4, Name 4 , 444444444
But I get this result..
ID: 0, Name 1 , 111111111
ID: 0, Name 2 , 22222222
ID: 0, Name 3 , 33333333
ID: 0, Name 4 , 444444444
after some searches I did not find any solution for that!
So what should I do to fix it ??
Thanks in advance!
EDIT
The stack-trace :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.muhamad_galal.databaseintro, PID: 3947
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.muhamad_galal.databaseintro/com.example.muhamad_galal.databaseintro.MainActivity}: java.lang.NumberFormatException: Invalid int: "null"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NumberFormatException: Invalid int: "null"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at Data.DataBaseHandler$override.getAllContact(DataBaseHandler.java:141)
at Data.DataBaseHandler$override.access$dispatch(DataBaseHandler.java)
at Data.DataBaseHandler.getAllContact(DataBaseHandler.java)
at com.example.muhamad_galal.databaseintro.MainActivity$override.onCreate(MainActivity.java:29)
at com.example.muhamad_galal.databaseintro.MainActivity$override.access$dispatch(MainActivity.java)
at com.example.muhamad_galal.databaseintro.MainActivity.onCreate(MainActivity.java)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077) 
at android.app.ActivityThread.-wrap15(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
What the message is saying is that you've passed a null to the Integer's parseInt method. as per :-
Caused by: java.lang.NumberFormatException: Invalid int: "null"
Thus it appears that the first column of the table has nulls.
At a guess you have not defined the column to be an alias of rowid and thus the column hasn't been given a unique integer value.
To be an alias of rowid it must be defined as INTEGER PRIMARY KEY or INTEGER PRIMARY KEY AUTOINCREMENT (the latter is not recommended).
If you changed :-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
// HERE is where the error come...
try{
if (cursor.getString(0) != null)
contact.setId(Integer.parseInt(cursor.getString(0)));
}catch (Exception e){e.printStackTrace();}
contact.setName(cursor.getString(1) );
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
to (see the comments at the end of lines that start with //<<<<) :-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT rowid,* FROM " + Util.TABLE_NAME; //<<<< CHANGED
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0)); //<<<< CHANGED to use getInt
contact.setName(cursor.getString(2)); //<<<< CHANGED to skip first column
contact.setPhoneNumber(cursor.getString(3)); //<<<< CHANGED to skip first column
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
Then I suspect that you would get the expected results.
This gets the normally hidden actual rowid column as well as all the other columns; so there is an extra column at the start.
Note this assumes that you haven't defined the table using WITHOUT ROWID
Really you should consider the id/rowid as a long but int will work as long as there aren't too many rows.
However, this should only be a temporary fix.
The full/permanent fix should be
Code the first column so that it is defined as an alias of rowid e.g. using CREATE TABLE you_table_name (ID INTEGER PRIMARY KEY, the_other_columns...... (this assumes that the column name is ID).
Delete the database by either uninstalling the App or by deleting the App's data.
This assumes that you do not require the current data.
Change the contact class so that the Id member is long not int.
Change the getters and setters in the contact class (setId and I assume getId) so that the methods use long rather than int
Change any other uses of the Id member of the contact class to use long.
Change the getAllContact method to be
:-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
delete the App's Data or uninstall the App.
rerun the App

How to use Belongs table in select

In laravel5 i belongsTo a model in a model that is
public function LeaveCategories()
{
return $this->belongsTo('App\LeaveCategories','leave_category_id','id');
}
Then i query in a controller that is
$userInfo = Leave::select(DB::raw('count(leaves.leave_category_id) as category_used'),
'LeaveCategories.id','LeaveCategories.category','LeaveCategories.category_num')
->where('Leaves.leave_date','>=', $first_day_this_year)
->where('Leaves.leave_date','<=', $last_day_this_year)
->where('Leaves.leave_status', 1)
->groupBy('Leaves.leave_category_id','LeaveCategories.category','LeaveCategories.category_num','LeaveCategories.id')
->get();
But it shows a error that is Unknown column 'LeaveCategories.id' in 'field list'
You use QueryBuilder, but belongsTo is ActiveRecord. Use that:
$userInfo = Leave::with('LeaveCategories')->where('Leaves.leave_date','>=', $first_day_this_year)
->where('Leaves.leave_date','<=', $last_day_this_year)
->where('Leaves.leave_status', 1)
->groupBy('Leaves.leave_category_id','LeaveCategories.category','LeaveCategories.category_num','LeaveCategories.id')
->get([DB::raw('count(leaves.leave_category_id) as category_used'),
'LeaveCategories.id','LeaveCategories.category','LeaveCategories.category_num']);

Zend Db query to select all IDs

How would I write an Zend DB query to select all from the column ID?
So far I have tried:
public function getLatestUserID()
{
$ids = $this->select()
->where('id = ?');
return $ids;
}
But to no avail.
You just want the id column,
You failed to call an execute command.
try:
//assuming you are using a DbTable model
public function getLatestUserID()
{
$ids = $this->fetchAll('id');
return $ids;
}
I would do it like this, because I use the select() object for everything:
public function getLatestUserID()
{
$select = $this->select();
//I'm not sure if $this will work in this contex but you can out the table name
$select->from(array($this), array('id'));
$ids = $this->fetchAll($select);
return $ids;
}
The first two examples should return just the id column of the table, now if you actually want to query for a specific id:
public function getLatestUserID($id)
{
$select = $this->select();
$select->where('id = ?', $id);
//fetchAll() would still work here if we wanted multiple rows returned
//but fetchRow() for one row and fetchRowset() for multiple rows are probably
//more specific for this purpose.
$ids = $this->fetchRow($select);
return $ids;
}
make sure your class containing getLatestUserID does extend Zend_Db_Table_Abstract also :
$ids = $this->select()->where('id = ?'); can't work because where('id = ?'); expects an id value like where('id = ?', $id);
if what you want is the latest inserted row's Id use :
$lastInsertId = $this->getAdapter()->lastInsertId();
(however if you are using an oracle database this will not work and you should use $lastInsertId = $this->getAdapter()->lastSequenceId('USER_TABLE_SEQUENCE'); )

Unable to execute insert statement while saving in symfony (propel) form with map list

In doSave() function in form I'm trying to save article category (which it is a node in a tree), and then assign to this category articles (many to many relationship).
I'm getting an error while in $this->saveWaArticleNewsCategoryMapList($con); line. (Project is builded on symfony 1.4.16). There is no error when I assign article to an existing category.
public function doSave($con = null) {
$scope = $this->getValue('tree_scope');
$toEdit = $this->getObject();
if ($toEdit->isNew()) {
$node = new ArticleCategory();
$node->setBrandId($this->getValue('brand_id'));
$node->setName($this->getValue('name'));
$node->setTreeScope($scope);
$root = ArticleCategoryQuery::create()->findRoot($scope);
if ($root == null) {
$root = new ArticleCategory();
$root->setName('Root');
$root->setTreeScopeIdValue($scope);
$root->makeRoot();
$root->save($con);
$node->insertAsLastChildOf($root);
$node->save($con);
return;
}
$parent = ArticleCategoryQuery::create()->findPk($this->getValue('parent_id'));
$node->insertAsLastChildOf($parent);
} else {
$node = ArticleCategoryQuery::create()->findOneByArticleCategoryId($toEdit->getArticleCategoryId());
$node->setBrandId($this->getValue('brand_id'));
$node->setName($this->getValue('name'));
if ($toEdit->getParent()->getArticleCategoryId() != $this->getValue('parent_id')) {
$parent = ArticleCategoryQuery::create()->findPk($this->getValue('parent_id'));
$node->moveToLastChildOf($parent);
}
}
$node->save($con);
$this->saveArticleNewsCategoryMapList($con); <--Error
$this->saveArticleHelpCategoryMapList($con);
}
Error:
Unable to execute INSERT statement [INSERT INTO `article_news_category_map` (`ARTICLE_ID`) VALUES (:p0)] [wrapped: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`projectname`.`article_news_category_map`, CONSTRAINT `article_news_category_map_FK_2` FOREIGN KEY (`category_id`) REFERENCES `article_category` (`article_category_id`) ON DELETE CASCADE)]
Updating ArticleCategoryId in object solved the problem:
$node->save($con);
$this->getObject()->setArticleCategoryId($node->getArticleCategoryId());
...

FunctionImport in entity framework 4 issue

I'm using entity framework 4.
I have a stored procedure that just updates one value in my table, namely the application state ID. So I created a stored procedure that looks like this:
ALTER PROCEDURE [dbo].[UpdateApplicationState]
(
#ApplicationID INT,
#ApplicationStateID INT
)
AS
BEGIN
UPDATE
[Application]
SET
ApplicationStateID = #ApplicationStateID
WHERE
ApplicationID = #ApplicationID;
END
I created a function import called UpdateApplicationState. I had initially set its return type to null, but then it wasn't created in the context. So I changed its return type to int. Now it was created in the context. Is it wise to return something from my stored procedure?
Here is my method in my ApplicationRepository class:
public void UpdateApplicationState(int applicationID, int applicationStateID)
{
var result = context.UpdateApplicationState(applicationID, applicationStateID);
}
Here is my calling code to this method in my view:
applicationRepository.UpdateApplicationState(id, newApplicationStateID);
When I run it then I get the following error:
The data reader returned by the store
data provider does not have enough
columns for the query requested.
Any idea/advise on what I can do to get this to work?
Thanks
To get POCO to work with function imports that return null, you can customize the .Context.tt file like this.
Find the "Function Imports" named region (the section that starts with region.Begin("Function Imports"); and ends with region.End();) in the .Context.tt file and replace that whole section with the following:
region.Begin("Function Imports");
foreach (EdmFunction edmFunction in container.FunctionImports)
{
var parameters = FunctionImportParameter.Create(edmFunction.Parameters, code, ef);
string paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
var isReturnTypeVoid = edmFunction.ReturnParameter == null;
string returnTypeElement = String.Empty;
if (!isReturnTypeVoid)
returnTypeElement = code.Escape(ef.GetElementType(edmFunction.ReturnParameter.TypeUsage));
#>
<# if (isReturnTypeVoid) { #>
<#=Accessibility.ForMethod(edmFunction)#> void <#=code.Escape(edmFunction)#>(<#=paramList#>)
<# } else { #>
<#=Accessibility.ForMethod(edmFunction)#> ObjectResult<<#=returnTypeElement#>> <#=code.Escape(edmFunction)#>(<#=paramList#>)
<# } #>
{
<#
foreach (var parameter in parameters)
{
if (!parameter.NeedsLocalVariable)
{
continue;
}
#>
ObjectParameter <#=parameter.LocalVariableName#>;
if (<#=parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"#>)
{
<#=parameter.LocalVariableName#> = new ObjectParameter("<#=parameter.EsqlParameterName#>", <#=parameter.FunctionParameterName#>);
}
else
{
<#=parameter.LocalVariableName#> = new ObjectParameter("<#=parameter.EsqlParameterName#>", typeof(<#=parameter.RawClrTypeName#>));
}
<#
}
#>
<# if (isReturnTypeVoid) { #>
base.ExecuteFunction("<#=edmFunction.Name#>"<#=code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))#>);
<# } else { #>
return base.ExecuteFunction<<#=returnTypeElement#>>("<#=edmFunction.Name#>"<#=code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))#>);
<# } #>
}
<#
}
region.End();
What I'm doing here is instead of ignoring all function imports that return null, I'm creating a method that returns null. I hope this is helpful.
It is because you do not actually returning anything from your stored procedure. Add a line like below to your SP (SELECT ##ROWCOUNT), and it will be executing properly.
BEGIN
...
SELECT ##ROWCOUNT
END
While this solution will address your issue and actually returns the number of effected rows by your SP, I am not clear on why this is an issue for you:
I had initially set its return type to null, but then it wasn't created in the context.
When doing a Function Import, you can select "None" as return type and it will generate a new method on your ObjectContext with a return type of int. This method basically executes a stored procedure that is defined in the data source; discards any results returned from the function; and returns the number of rows affected by the execution.
EDIT: Why a Function without return value is ignored in a POCO Scenario:
Drilling into ObjectContext T4 template file coming with ADO.NET C# POCO Entity Generator reveals why you cannot see your Function in your ObjectContext class: Simply it's ignored! They escape to the next iteration in the foreach loop that generates the functions.
The workaround for this is to change the T4 template to actually generate a method for Functions without return type or just returning something based on the first solution.
region.Begin("Function Imports");
foreach (EdmFunction edmFunction in container.FunctionImports)
{
var parameters = FunctionImportParameter.Create(edmFunction.Parameters, code, ef);
string paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
// Here is why a Function without return value is ignored:
if (edmFunction.ReturnParameter == null)
{
continue;
}
string returnTypeElement = code.Escape(ef.GetElementType(edmFunction.ReturnParameter.TypeUsage));
...