How to delete multiple rows? - database

So I can delete one row using:
$this->db->delete($tableName,array("id"=>4));
...but I can't figure out how to delete multiple rows. I tried:
$this->db->delete($tableName,array("id"=>4,"id"=5));
as well as:
$this->db->delete($tableName,array(array("id"=>4),array("id"=5)));
...but they both don't work. I feel like this should be pretty easy. Any answers?

Have you tried this ?
$names = array(4,5);
$this->db->where_in('id', $names);
$this->db->delete('mytable');

not need of associative array.
$ids[] = 1;
$ids[] = 2;
$this->db->where_in( id, $ids );
$this->db->delete('Table_Name');

write custom query for it
$this->db->query("DELETE FROM `TABLE_NAME` WHERE `id` IN(1,2,3,4,5)");

it is not work
$names = array(4,5);
$this->db->where_in('id', $names);
$this->db->delete('mytable');
DELETE FROM table_name WHERE id IN ('4,5')
notice one thing not single string/digit ('4,5') we should be dived each and every id with single quotation like this ('4','5')
The best and good way
//$ids = 1,2,3.....
$ids_exp = explode(',',$ids);
$this->db->where_in('id',$ids_exp);//
$this->db->delete('table_name')
return $this->db->affected_rows();
the above query will be work enjoy..........

To delete a single use row:
$this->db->delete('TABLE_NAME', array('id' => 5));
Have you tried doing this? I'm pretty sure it should work.
$this->db->delete('TABLE_NAME', array(array('id' => 5), array('id' => 3), ...));

This is an old question, but I'll answer it since I had to research the same question 8 years later.
I checked the source code of $wpdb->delete(), and it will basically only delete 1 row. It works by matching 1 col to 1 val, and then joining with AND. So if you do array("id"=>4,"id"=>5), it will read it as row with (id==4 AND id==5). No rows will match that condition.
So to delete multiple rows, the only way (as far as i've seen) is to use a custom query:
$wpdb->query("DELETE FROM `TABLE_NAME` WHERE `id` IN(1,2,3,4,5)");

Related

Delete column in WordPress database table

I want to delete a column from a table in WordPress.
I tried many ways but either they don't work or they delete the whole row.
But I just want to remove the status column.
I have a lot of tables and I can't delete them manually.
Is there a solution in WordPress?
I used the following code but it doesn't work and it doesn't remove the column
function remove_status_database()
{
$table_name ="wp_order_status";
$column_name = "status";
$drop_ddl = true;
maybe_drop_column($table_name , $column_name ,$drop_ddl );
}
Example of the image .
Have you tried to do it with https://de.wordpress.org/plugins/wp-optimize/ ?
you can simple select the specific table and remove it.
hth
Stefano
I found the answer to my question. I can do a column with the following sql command.
$wpdb->query("ALTER TABLE wp_order_license DROP status" );

Reduce arrays where values are equals

It's a simple question I think, but i can't handle this.
If you see the image, here is my DB with multiple Usernames and "instances_id". If I var_dump this I have 11 arrays (and that's normal).
Is there a way to reduce arrays where "instance_id" is equal?
So that I have the first array containing "Alessio,Giorgio", the second one "Alessio,Giovanni" etc.
I use laravel... I hope you can help me
You could use combination of GROUP BY with GROUP_CONCAT to retrieve directly from db:
$result = DB
::table('example')
->selectRaw('instance_id, GROUP_CONCAT(Username)')
->groupBy('instance_id')
->get();
Or via laravel collection:
$result = DB::table('example')->get();
$result = $result
->groupBy('instance_id')
->map(function($group){
$data = $group->first();
$data->Username = $group->pluck('Username')->implode(',');
return $data;
})
->values();
Try..
SELECT * FROM tableName GROUP BY fieldName;
The following query will select all fields along with distinct zip field.
There are two ways.
1)select *
from table
group by field1
2) select distinct on field1 *
from table

Remove overlap entries from postgres arrays

I am trying to remove entries from an array field that are found in a query.
tablename.listfield::integer[] has a full list
I am trying to remove a list of values from that field, which are gathered within the update query.
the ARRAY_REMOVE method only accepts single values, and the intarray module which has int[] - int[] doesn't seem to be an option.
the ARRAY[] && ARRAY[] can boolean return if there is overlap, but that doesn't help me
basically what I need is a real working version of this concept, which I know does not work.
UDPATE tablename SET listfield = ARRAY_REMOVE( listfield, ( select id from othertable ) )
is it possible to get this done with maybe a tricky CTE setup or something?
thanks!
I'm not sure why you say intarray doesn't seem to be an option, because it works just fine:
... SET listfield = listfield - ( SELECT array_agg(id) FROM othertable )
But if you want to do this without installing the extension, you can UNNEST the array and use the EXCEPT construct:
... SET listfield = ARRAY(SELECT UNNEST(listfield) EXCEPT SELECT id FROM othertable)

arrays and mysqli insert

once again thanks for your help in advance im looking to pre fill a mysqli insert statement with data filled from an array and cannot seem to get it to work it just doesnt insert and im kinda stuck and looking for ideas
this is what im chasing as a end result as for code but cannot seem to get it to work
$table_colums= array("db_colum1","db_colum2");
$forms_data = array("form_data1","form_data2");
$sql = INSERT into some_table ($table_colums) VALUES ($forms_data)
obviously if i do it the old fashion way it will work but i need to have it get its values from the arrays because there dynamic and filled from a database
$sql = INSERT into some_table (db_colum1,db_colum2) VALUES ('form_data1','form_data2')
I can suggest you a library I wrote, SafeMysql, which is doing exactly what you want - adding arrays to mysql (among many other wonderful things).
Though you need another kind of array, but I suppose it would be even simpler:
include 'safemysql.class.php';
$db = new safemysql();
$data = array(
"db_colum1" => "form_data1",
"db_colum2" => "form_data2",
);
$db->query("INSERT INTO some_table SET ?u", $data);
Nothing could be easier.

I need to count the today created account in Cake 3

I need to count the users, but my condition is only if their account have been created today. I have a users table with a created field (datetime) for each rows. How can i do it in Cakephp, i didn't find the answer in the documentation.
$usersNewCount = Number::format($this->Users->find()->where(['created' => 'CURDATE()'])->count());
I tried with CURDATE, and of course it's not working, i guess Cakephp has a specific function for te datetime field ?
What you are doing there won't work for various reasons.
You cannot pass SQL snippets in the value part of the conditions array, it will be escaped and you'll end up with a string comparison like created = 'CURDATE()', you'd either have to pass the whole condition as a string, or use raw expressions.
Even when properly passing CURDATE(), the comparison won't work as the created column has a time part.
While it is possible to circumvent the former problem by transforming the column, you should try to avoid that whenever possible! Comparing to calculated columns like DATE(created) = CURDATE() will make using indices impossible, and thus massively degrade performance!
So unless you have an extra column that holds just the date part, your best bet is a BETWEEN comparison which is the equivalent to a >= x AND a <= y, and in order to stay cross DBMS compatible, this is best to be done by passing dates from PHP, ie not using DBMS specific date and time functions like CURDATE().
$this->Users
->find()
->where(function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) {
$from = (new \DateTime())->setTime(0, 0, 0);
$to = (new \DateTime())->setTime(23, 59, 59);
return $exp->between('Users.created', $from, $to, 'datetime');
})
->count()
This will create a query similar to
SELECT
(COUNT(*)) AS `count`
FROM
users Users
WHERE
Users.created BETWEEN '2015-05-26 00:00:00' AND '2015-05-26 23:59:59'
See also
API > \Cake\Database\Expression\QueryExpression::between()
You can do it this way
$usersNewCount = Number::format($this->Users->find()->where([
'DATE(created) = CURDATE()'
])->count());
Note that passing it in form where(['DATE(created)' => 'CURDATE()']) will not work, since CURDATE() will be interpreted as a string.
When doing 'created' => 'CURDATE()' you are checking for a complete match, getting '2015-05-26', without a time. You need to check for a time interval:
$usersNewCount = Number::format(
$this->Users->find()->where([
'created >=' => date('Y-m-d').' 00:00:00',
'created <=' => date('Y-m-d').' 23:59:59'
])->count());

Resources