Multiple Queries in Codeigniter [duplicate] - codeigniter

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MYSQL multiple insert in codeigniter
I would like to execute multiple insert queries simultaneously using codeignitor framework in PHP.There is any simple ways to do this without writing multiple insert queries.Already tried something like
$this->db->query('INSERT INTO students (first_name, last_name) VALUES
('teejay', 'obazee')'
('maev', 'shadowsong')'
('jaina', 'proudmore')', FALSE)
.There is any ways like this.Which is not working.If anybody knows;please help me.

You can use codeignitor native active record
$data = array(
array(
'first_name' => 'teejay', 'last_name' => 'obazee'
),
array(
'first_name' => 'maev', 'last_name' => 'shadowsong'
),
array(
'first_name' => 'jaina', 'last_name' => 'proudmore'
)
);
$this->db->insert_batch('students', $data);
It will produce query
INSERT INTO students (first_name,last_name) VALUES ('teejay', 'obazee'),('maev', 'shadowsong'),('jaina', 'proudmore');

I also had problem with sending multi queries in CodeIgniter.
In your specific situation, you could send multi rows in one INSERT query, but in many other situations this is not possible because you have different commands (eg LOCK TABLE... SELECT... INSERT... UPDATE... UNLOCK TABLES)
At that point in codeigniter you should user:
mysqli_multi_query($this->db->conn_id, $sql);
I didn't even know the answer, the answer was originally posted as a comment by Kumar (https://stackoverflow.com/users/523794/kumar) at Codeigniter - how to run multiple/batch queries?
Note: You have to set you database driver to mysqli in /application/config/database.php
Hope it helps some one.

Unfortunately, you need to do something like:
$this->db->query("INSERT INTO `students` (`first_name`,`last_name`) VALUES ('teejay', 'obazee'),('maev', 'shadowsong'),('jaina', 'proudmore')");
Or use someone else's class to build the query:
http://codefury.net/2009/12/insert-multiple-rows-into-a-database-with-codeigniter/

Related

How to add validation for preventing duplicate level points in laravel query?

Here is a table named stages and below are the fields
I don't want to allow to add the same from and to points example, if points from 1 to 10 is already added means not allow them to add the same range, another one condition is don't allow to add in between points example in-between 1to 10 like 5 to 7 are also not allowed.
Tried laravel query
$isexist = Stage::whereBetween('from', [$request->from, $request->to])
->orWhereBetweenColumn('to','from', [$request->from, $request->to])->exists();
but it not satisfying all conditions.
Any one please help, thanks in advance.
you can validate the data like this
$validator = Validator::make($inputData, [
'label' => 'required|unique:tableName,label'
]);
if($validator->fails()){
//Throw validation errors
}
Or you can use
Model::query()->updateOrCreate(['label' => $request->label], [
'from' => $request->from,
'to' => $request->to
]);
Read more on unique validation reference: https://laravel.com/docs/9.x/validation#quick-writing-the-validation-logic

Codeigniter - Multiple database prefixes

I'm in process to migrate an old webapp to codeigniter, everything looks good other then that the database has 3 kind of tables with different table prefixes.
the app's native tables use mci_ as prefix
tables which hold inter departmental data (kind off) use mdept_
and tables handling non-native data use mext_ as prefix
now as I understand we can set one prefix for entire database
'hostname' => DB_HOST,
'username' => DB_USER,
'password' => DB_PASS,
'database' => DB_NAME,
'dbdriver' => 'mysqli',
'dbprefix' => 'mci_',
and query builder will use mci_ for all tables.
My question is, is there a way to use rest of the 2 prefixes (mdept_, mext_) with query builder rather then having the direct approach db->query
Thanks
Solution #1:
You can set $this->db->dbprefix = "mdept_" before $this->db->select()...get();. But this will work if there is only one table in the query. And if there are other queries below, then you also need to redefine dbprefix again.
Solution #2:
Add for mdept_... and mext_... tables the prefix mci_. I.e mci_mdept_users. No need to change the database config, redefine the prefix, just specify the table names in the queries along with the old "prefixes".
Solution #3:
Delete prefix in config at all: 'dbprefix' => '', and use full table names with prefixes in queries.
Solution #4. The best solution of these, in my opinion
Add a view with the mci_ prefix to your database: CREATE VIEW mci_old_mdept_users AS SELECT * FROM mdept_users;. All that the view will do is to get data from a table that you cannot rename. And in your application you can write simply: $this->db->get('old_mdept_users');.
Solution #5. If all queries use tables with the same prefixes
Divide tables into 3 databases. Add these databases in the config:
$db['default'] = array(
...
'dbprefix' => 'mci_',
...
);
$db['mdept'] = array(
...
'dbprefix' => 'mdept_',
...
);
$db['mext'] = array(
...
'dbprefix' => 'mext_',
...
);
Add other connections in MY_Model:
protected function connect_mdept_db()
{
$this->mdept_db = $this->load->database('mdept', TRUE);
}
Use these connections:
$this->connect_mdept_db();
$this->mdept_db->get("users"); // uses "mdept_users" table

Sorting in Yii2

i'm trying to get data from joined tables sorted by specific column. This column is a varchar column but contain only numbers.
The sorting is not working and i have done a lot of research. Please can anyone help me.
what i need is to sort an ActiveDataProvider instance.
this is my code :
$dataProviderItems = new ActiveDataProvider([
'query' => Products::find()->innerJoin('products_trans', 'products_trans.PRODUCT_ID=products.PRODUCT_ID')->innerJoin('items', 'items.PRODUCT_ID=products.PRODUCT_ID')->innerJoin('items_supplieirs', 'items.ITEM_ID=items_supplieirs.ITEM_ID')->innerJoin('suppliers', 'items_supplieirs.SUPPLIER_ID=suppliers.SUPPLIER_ID')->innerJoin('items_trans', 'items_trans.ITEM_ID=items.ITEM_ID')->andFilterWhere(['products_trans.PRODUCT_ID' =>$productID]) ,
'pagination' => false,
'sort'=> ['defaultOrder' => ['cast(items_supplieirs.PRICE as unsigned)'=>SORT_ASC]]
]);
thanks in advance, best regards.

unique between 2 columns

i need to create a validation to my table "candidate_knowledges", basically in this table it accepts to columns (candidate_id, software_id), i cannot let create user_id and software more then one. but i think my validation is wrong or im not doing it right.
What im trying to say in validation is that can only exist one software_id and one candidate_id on the table, this way the candidate dont have duplicate entries.
Ex: 'software_id' => 'required|integer|unique:candidate_knowledges,candidate_id,'.$candidate->id,
Here is a way to allow only one software for each candidate:
$rules = [
'software_id' =>
'required',
'integer',
'min:1',
Rule::unique('candidate_knowledges')->where('candidate_id', $candidate->id),
],
];
In general I would suggest using fluent validation syntax (it's match easier to use and update), but if you can't (laravel < 5.3 or any other reasons):
'software_id' => 'required|integer|unique:candidate_knowledges,NULL,NULL,candidate_id,' . $candidate->id,
Hope it helps.

Seeding and pivot tables?

I'm trying to popular a pivot table with ids in a seed.
$id = DB::table('products')->insertGetId(array(
array(
'title' => 'Product A',
'published' => 1
)
));
DB::table('product_user')->insert(array(
array(
'product_id' => $id,
'user_id' => '9999999999'
)
));
Is the above the best way to do it? By getting an id via insertGetId and then putting it in the pivot table Is there a better way?
Also the above way gives an error:
[ErrorException]
preg_replace(): Parameter mismatch, pattern is a string while replacement i
s an array
I suspect $id is an array, how can i get InsertGetId to return an int?
Well, you can print_r it and seek for the id attribute, and then call $id->attribute on the second insert.
But...
"Me myself", I like to use Eloquent. The mainly reason is: 'Cause it too god damm FUN. Really, Eloquent it's one of the most beautful things I've ever seen in the programming world. I use to thought that .NET was a master piece of software (I was young and naive, though) but once a came across Laravel/Eloquent, I became so AMAZED!
That being said, in my humble opinion, use Eloquent is the best way of doing it!
I'm assuming that you have a table called products and another called users, and you have a product_user table to make the connection. Using Eloquent, you can simply do this:
$user = User::find($user_id);
$product = Product::find($product_id);
$product->user->attach($user);
...I reacomend this approach for several reasons, but the first one is: is way more readable.
Well, I hope I ain't been too prolixous on my answer, and that it hope you and others.

Resources