Laravel 5: insert row with possibility of duplication - php

How to insert row with possibility of duplication in unique column and return if item inserted or not?
tried:
$id = DB::insert("INSERT IGNORE INTO question (id,text) values (10,'test')");
but $id always return with value = 1
tried also:
$id = DB::table('question')->insertGetId(['id' => 10, 'text' => 'test'])->ignore();
but ignore() has no effect!

try {
DB::table('arv_groups')->insert([
'grouphash' => $grouphash,
'id_photo' => $id
]);
} catch(\Illuminate\Database\QueryException $e){
// I DON'T CARE IT'S DUPLICATE !!! THANK YOU VERY MUCH!
}

Related

Compare array to db and add difference to db

I'm using codeigniter.
I'm trying to compare some posted values from a form with entries from a database.
Put simply, i want to check to see if the entry is already in the database, if so ignore the posted data, but if there is no database entry then add to the database.
My thinking was that it shouldn't actually be that hard, but having some issues, and now im completely confused. Any pointers in the right direction would be appreciated.
I have an array coming from POST $assigned_ids
And i want to compare that with the data from $assign_data which is being output from the database.
I've been trying foreach loops, looping over the posted data, and then inside that looping through the database and comparing and adding if neccessary.
It works upto a point, but if there is data coming from the database, its adding multiple entires.
Heres my code, surely im over complicating things?
// posted values foreach - loop through all posted values
foreach($assigned_ids as $id) {
if(is_array($assign_data) && count($assign_data) > 0) {
// query all data in assignments table
foreach($assign_data as $key => $value) {
// is the user id from assignments table in posted id's
if(in_array($value->user_id, $id)){
// if it is, then do the course id's match as well? if so, do nothing, already an entry
if($value->course_id == $course_id) {
echo "match id and course, do nothing";
} else {
// else if there isnt an entry for this user for this course, add the entry
$add_data = array(
'user_id' => $value->user_id,
'course_id' => $course_id,
'org_id' => $org_id
);
$this->assignment_model->save_org_assignments($add_data);
}
} else {
// the user id was not in the array from the db, but was in the posted vars, so log in db
$add_data = array(
'user_id' => $id,
'course_id' => $course_id,
'org_id' => $org_id
);
$this->assignment_model->save_org_assignments($add_data);
}
}
} else {
$add_data = array(
'user_id' => $id,
'course_id' => $course_id,
'org_id' => $org_id
);
$this->assignment_model->save_org_assignments($add_data);
}
}
I think your main issue is your array is not properly structured that's why your having a hard time.
My opinion is to predefined your db result after fetching it.
function getAssignedData(){
// its better to get the only field you'll need than to fetch everything
$result = $this->db->select($field)->get();
if($result->num_rows()){
$existing_ids = [];
foreach($result->result() as $row){
$existing_ids[] = $row->$field;
}
return array_flip($existing_ids);
}
return FALSE;
}
And you can already compare the values like this
foreach($assigned_ids as $id)
{
if(!isset($existing_ids[$id])) {
// do something
}
}
Hope that helps.

Update only one record with Code Igniter

Firstly, I will show what I want to do.
I want check if user has more than one record:
WHERE 'from_user_id' == '$id'
When query return > 0, I want update only ONE record where 'from_user_id' == '$id',
I dont care about order, It can be last or first record, but I have to update only one record.
Here is part of my model:
public function get_bonuses() {
if ($this->db->where('from_user_id', $this->user_id())->from($this->reff_table)->count_all_results()>0 ) {
$this->db->where('from_user_id', $this->user_id());
$this->db->update($this->reff_table, array('used' => '1'));
return true;
} else
return false;
}
It works fine but I want update only one record :<
I hope anyone will help me.
Regards
----- EDIT
SOLVED - I'm so stupid but I needed to look from the other side to my code :)
Here is working code:
if ($this->db->where(array('from_user_id' =>$this->user_id(), 'used' => '0' ))->from($this->reff_table)->count_all_results()>0 ) { $this->db->where(array('from_user_id' =>$this->user_id(), 'used' => '0' ))->limit(1); $this->db->update($this->reff_table, array('used' => '1')); return true;
If you want to update any one record from result, simply limit the query where you check count to 1 & grab its unique id (primary key) and update that row.

How do I get the last id from a table after multiple insert

I am adding data to three tables, I needed to get the last ID of the first table to use in the second table, which was successful with $this->db->insert_id() function, Trying that with the second table still gives me the ID of the first table. The arrangement of my code is:
function addcrm() {
//Post data collection array from the webform form
$customerdata = array(
"salutation"=>$this->input->post('salutation'),
"mobilenumber"=>$this->input->post('mobilenumber'),
"emailaddress"=>$this->input->post('emailaddress')
);
$this->db->insert('api_customer', $customerdata);
$customer=$this->db->insert_id();
$leaddata = array(
"fieldrep"=>$this->input->post('fieldrep'),
"fk_customerID"=>$customer,
"te"=>$this->input->post('takage'),
"othercost"=>$this->input->post('othercost')
);
$this->db->insert('api_lead', $leaddata);
$leadID = $this->db->insert_id();
for ($i =0; $i<count($_POST['w_product']); $i++){
$productdata = array(
"name" => $_POST['w_product'][$i],
"type" => $_POST['w_type'][$i],
"cost" => $_POST['w_cost'][$i],
"fk_leadID"=> $leadID
);
$this->db->insert('api_prod',$productdata);
}
$url = base_url('cXXXXXXXXXXXXXX);
redirect($url);
}
You are missing something obviously in the second call. ;)
$customer = $this->db->insert_id();
$leadIdD = $this->db->insert_id;
See? :)
Try working with the following methods:
$this->db->start_cache(); // Before query
$this->db->stop_cache(); // After query
$this->db->flush_cache(); // Clear query
This way you make clear and flushed queries.
if you are using an auto increment table you may try using MYSQL_LAST_INSERT_ID();
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

How to check records already exist in database when u save new record?

I want to add the new records in table if proudct_id and plan_id is already exist in same row then the error occur otherwise it save the record. I have written following lines of code but no success, if there is any help so please, thanks. I am doing it in cakephp
function admin_product_plan_add(){
$exists = $this->ProductPlan->find('all');
$this->set('exists',$exists);
foreach ($exists as $exists){
$plan_id = $exists['ProductPlan']['plan_id'];
$product_id = $exists['ProductPlan']['product_id'];
}
$conditions = array('ProductPlan.product_id' => $plan_id, 'ProductPlan.plan_id' => $product_id);
$data = $this->ProductPlan->find('all' , array('conditions'=>$conditions));
if (isset($data) && !empty($data))
{
echo '<p>User have already add this product plan!</p>';
}else{
if ($this->ProductPlan->save($this->data)){
$this->Session->setFlash('You have successfully add the product plan');
$this->redirect(array('controller' => 'productplans','action' => 'admin_product_plan_list'));
}
}
}
Use hasAny()
something like:
public function admin_product_plan_add(){
if($this->ProductPlan->hasAny(array("product_id" => $this->data['ProductPlan']['product_id'],'plan_id' => $this->data['ProductPlan']['plan_id']))){
// USER ALREADY HAVE THIS PRODUCTPLAN
} else {
//CREATE NEW PRODUCTPLAN
}
}
or something like that.
Hope this helps
One solution is to use a uniq index over these two rows. So when someone tries do add another row with the same data on these two rows, mysql throws an error and the data is not inserted.

$this->db->insert_id() seems to be wiping away my previous insert_id variables value

Here is the code:
$the_question = $_POST['question'];
$the_answer = $_POST['answer'];
$dummy_num[] = $_POST['dummy_answer_1'];
$dummy_num[] = $_POST['dummy_answer_2'];
$dummy_num[] = $_POST['dummy_answer_3'];
//Get Hidden Test ID and Q_order
$test_id = $_POST['test_id'];
$q_order = $_POST['q_order'];
//Submit Question
$data_submit_q = array (
'type' => 1,
'question' => $the_question,
'done' => 1
);
$this->db->where('test_id', $test_id);
$this->db->where('q_order', $q_order);
$this->db->update('questions', $data_submit_q);
$question_id = $this->db->insert_id();
$time_created = date('Y-m-d H:i:s');
//Submit Answer
$data_submit_a = array (
'test_id' => $test_id,
'question_id' => $question_id,
'option' => $the_answer,
'company_id' => $data['company']->id,
'job_id' => $data['session_job_id'],
'time_created' => $time_created
);
$this->db->insert('options', $data_submit_a);
$answer_id = $this->db->insert_id();
//Let question know that answer is right.
$data_submit_qr = array (
'answer_id' => $answer_id
);
$this->db->where('id', $question_id);
$this->db->where('test_id', $test_id);
$this->db->update('questions', $data_submit_qr);
Setting the answer id removes the value of the question id, then on updating the database the answer id has no value also. Even though it does right before.
The method $this->db->insert_id() retrieves the ID when performing database inserts (as the name hints).
You're using it after an update, that's why your $question_id gives problems (I think it would be set to FALSE, but I don't know for sure what does that method return when called on the wrong context). WHen you do your last update you use this as a WHERE condition, and if it is not set...
It's not that your second call to insert_id() wipes out the first, I suspect is more like the first one is already NOT SET (or FALSE)
It seems that there is a bug with insert_id, you can try using:
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$lastInsertId = $row['LAST_INSERT_ID()'];
Hope it helps

Categories