How to add foreign key value in insert query - mysql - CodeIgniter - mysql

I have the following insert query:
$salarystuff = array('salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
The salary table has columns: emp_no| salary| from_date| to_date (I'm using the database available from dev.mysql.com.
But it gives me an error 1452 saying foreign key constraint. How do I reference to the key value in the other table to be able to insert into this table?
This is the error message:
Cannot add or update a child row: a foreign key constraint fails
(employees.salaries, CONSTRAINT salaries_ibfk_1 FOREIGN KEY
(emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE)
INSERT INTO salaries (salary, from_date, to_date) VALUES
('1000000', '2012-12-27', '2013-01-16')
Thank you
edit: I'm trying the following
First I create the record in the employees table using this function:
function add_emp($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate)
{
$data = array( 'first_name' => $firstname,
'last_name' => $lastname,
'gender' => $gender,
'birth_date' => $date_of_birth,
'hire_date' => $hiredate);
$this->db->trans_start();
$this->db->insert('employees', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
$msg = "Adding the new employee failed.";
return $msg;
}
else
{
$msg = "Successfully Added Employee.";
return $msg;
}
}
and then in another function I add the salary:
function add_salary($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate,$salary, $salary_from_date,$salary_to_date)
{
$this->db->select('emp_no');
$this->db->from('employees');
$this->db->where('first_name', $firstname);
$this->db->where('last_name', $lastname);
$this->db->where('gender', $gender);
$this->db->where('hire_date', $hiredate);
$this->db->where('birth_date', $date_of_birth);
$this->db->limit(1);
$selected_employee = $this->db->get();
$salarystuff = array('emp_no' => $selected_employee, 'salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
}
both of which are in the model. Then in the controller I call both functions:
$employee_insert = $this->user->add_emp($firstname,$lastname,$gender,$date_of_birth,
$jobtitle,$dept, $hiredate);
$salarythings = $this->user->add_salary($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate,$salary, $salary_from_date,$salary_to_date);
But I get an error because there is no value in the emp_no field...I think it might be the line:
$selected_employee = $this->db->get();
$salarystuff = array('emp_no' => $selected_employee,
My error message is:
Object of class CI_DB_mysql_result could not be converted to string

The problem is you are trying to insert into the salaries table, but you aren't specifying what employee the salary record is for. You would need to provide a value for the emp_no column that is in the employees table.
ETA:
Glad you posted more code - what you should do is modify your add_emp function so that it returns the id of the employee that was created (I'm assuming here that emp_no is and auto-increment column in your database). Like so:
function add_emp($firstname,$lastname,$gender,$date_of_birth,$jobtitle,$dept,$hiredate)
{
$data = array( 'first_name' => $firstname,
'last_name' => $lastname,
'gender' => $gender,
'birth_date' => $date_of_birth,
'hire_date' => $hiredate);
$this->db->trans_start();
$this->db->insert('employees', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
//$msg = "Adding the new employee failed.";
//return $msg;
return -1; // indicates failure
}
else
{
//$msg = "Successfully Added Employee.";
//return $msg;
return $this->db->insert_id();
}
}
Note that the code that calls add_emp will need to change a bit to look at the return value as an integer instead of a message now, but now you have the id of the employee and you can use that in your add_salary function instead of having to pass in all that other data, like so:
function add_salary($emp_no,$salary, $salary_from_date,$salary_to_date)
{
$salarystuff = array('emp_no' => $emp_no, 'salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);
}
So the code to add an employee and their salary would be something like this:
$emp_no = add_emp([Your parameters]);
if ( $emp_no > 0 ) {
add_salary($emp_no, [other parameters]);
} else {
// Show some error message that the employee creation failed.
}
EDIT AGAIN:
If you ignore my advice above, the simple answer to why you are getting an error is because $selected_employee is a result set and not an actual employee number. You would need to change that code like so:
$selected_employee = $this->db->get();
$result = $selected_employee->result();
$emp_no = $result[0]->emp_no;
$salarystuff = array('emp_no' => $emp_no, 'salary' => $salary, 'from_date' => $salary_from_date, 'to_date' => $salary_to_date);
$this->db->insert('salaries', $salarystuff);

Related

Codeigniter: Know AI ID of query

When a user create an item, on my controller i need to send 2 SQL Query.
The first is easy to do:
$data = array(
'author' => $this->input->post('author'),
'name' => $this->input->post('name'),
);
$this->item_model->insertItem($data);
But on my second query, i need to recover, to find the ID of the query showing just before.
For example:
$data = array(
'user_id' => $_SESSION['user_id'],
'item_id' => ????,
);
$this->item_model->insertItem($data);
Thanks
For fetching the last inserted ID of variable $item_id in the same transaction of your controller, you can get the ID of record in the same session as follows:
$item_id = $this->db->insert_id();

BEGIN,INSERT,COMMIT with ON DUPLICATE KEY UPDATE

I have two tables:
1- beoordelingen
2 - sterren
I need to update 3 values in table beoordelingen and insert new values into table sterren
How do I do that?
ON DUPLICATE KEY doesn't work and I can't find anywhere how to do it.
$sql=$dbo->prepare("BEGIN;INSERT INTO beoordelingen(beoordelingid,userid,werkid,inlijn,
sjabloon,conclusie,save)
VALUES ('$beoordelingid','$user','$werkid','$inlijn','$sjabloon','$conclusie','0')
ON DUPLICATE KEY UPDATE
beoordelingid=VALUES(beoordelingid),userid=VALUES(userid), werkid=VALUES(werkid),
inlijn=VALUES(inlijn),sjabloon=VALUES(sjabloon),conclusie=VALUES(conclusie),
save=VALUES(save);
INSERT INTO sterren (beoordelingid,userid,werkid,titelwerk,actie,sterren)
VALUES ('$beoordelingid','$user','$id','$titelwerk',
'$actie','$sterren'); COMMIT");
I adapted the following. The insert1 still won't work. Insert2 works
$dbo->beginTransaction();
//NOT WORKING
$insert1 = $dbo->prepare("INSERT INTO beoordelingen(beoordelingid, userid, werkid, inlijn, sjabloon, conclusie, save)
VALUES (:beoordelingid, :user, :werkid, :inlijn, :sjabloon, :conclusie, '0')
ON DUPLICATE KEY UPDATE
beoordelingid=VALUES(beoordelingid),
userid=VALUES(userid),
werkid=VALUES(werkid),
inlijn=VALUES(inlijn),
sjabloon=VALUES(sjabloon),
conclusie=VALUES(conclusie),
save=VALUES(save);"
);
//THIS WORKS
$insert2 = $dbo->prepare("INSERT INTO sterren (beoordelingid, userid, werkid, titelwerk, actie, sterren)
VALUES (:beoordelingid, :user, :id, :titelwerk, :actie, :sterren);"
);
//NOT WORKING
$insert1->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'werkid' => $werkid,
'inlijn' => $inlijn,
'sjabloon' => $sjabloon,
'conclusie' => $conclusie,
'save' => $save
));
//THIS WORKS
$insert2->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'id' => $werkid,
'titelwerk' => $titelwerk,
'actie' => $actie,
'sterren' => $sterren
));
$dbo->commit();
My last problem:
$sterren=$_POST['sterren'];
$user=$_REQUEST['user'];
$userid=$_POST['userid'];
$actie=$_POST['actie'];
$dbo->beginTransaction();
//THIS WORKS
$insert1 = $dbo->prepare("INSERT INTO sterren(sterren,userid,actie)
VALUES (:sterren, :userid, :actie);"
);
//THIS DOESN"T WORK
$insert2 = $dbo->prepare("INSERT INTO sterren(sterren,userid,actie)
VALUES (:-sterren, :user, :actie);"
);
//THIS WORKS
$insert1->execute(array(
'sterren' => $sterren,
'userid' => $userid,
'actie' => $actie
));
//THIS DOESN"T WORK
$insert2->execute(array(
'-sterren' => $sterren,
'user' => $user,
'actie' => $actie
));
$dbo->commit();
This is not how to use prepared statements (->prepare()) or how to use a transaction with PDO.
First off, prepare() is for "preparing" one SQL query with placeholders so that you can pass the parameters in a later function (execute()) and avoid SQL injection from concatenating strings.
Second, if you want to use a transaction then you should use PDO's beginTransaction and commit functions.
Try something like this:
$dbo->beginTransaction();
$insert1 = $dbo->prepare('INSERT INTO beoordelingen(beoordelingid, userid, werkid, inlijn, sjabloon, conclusie, save)
VALUES (:beoordelingid, :user, :werkid, :inlijn, :sjabloon, :conclusie, :save)
ON DUPLICATE KEY UPDATE
beoordelingid=VALUES(beoordelingid),
userid=VALUES(userid),
werkid=VALUES(werkid),
inlijn=VALUES(inlijn),
sjabloon=VALUES(sjabloon),
conclusie=VALUES(conclusie),
save=VALUES(save);'
);
$insert2 = $dbo->prepare('INSERT INTO sterren (beoordelingid, userid, werkid, titelwerk, actie, sterren)
VALUES (:beoordelingid, :user, :id, :titelwerk, :actie, :sterren);'
);
$insert1->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'werkid' => $werkid,
'inlijn' => $inlijn,
'sjabloon' => $sjabloon,
'conclusie' => $conclusie
));
$insert2->execute(array(
'beoordelingid' => $beoordelingid,
'user' => $user,
'id' => $id,
'titelwerk' => $titelwerk,
'actie' => $actie,
'sterren' => $sterren
));
$dbh->commit();

Which is better option to avoid duplicate insertion: delete and insert or check and insert?

Just got one doubt while performing insert operation. I want to keep records to be unique. So while inserting record currently I am executing delete() function to delete same record if exists and then using insert() function. But just thought that if I check that record is exists and insert only if that record not found. So I can avoid delete() operation. So which is better option?
This is my code.
public function insertPostLike($postId = null, $userId = null) {
//This is to avoid duplicate entry for same user.
$this->_db->delete($this->_name, array(
'post_id = ?' => $postId,
'user_id = ?' => $userId));
$result = '';
$arrData = array(
'post_id' => $postId,
'user_id' => $userId,
'liked_date' => Zend_Date::now()->toString('yyyy:MM:dd HH:mm:ss')
);
if (!is_null($postId)) {
$result = $this->insert($arrData);
}
return $result;
}
I am using zend framework.

Database Error Occurred Error Number: 1062

i tried to make option update three table with one execution for my CI with sql there, but why its still error?
this is the error warning:
A Database Error Occurred
Error Number: 1062
Duplicate entry '0' for key 1
UPDATE `t_publisher` SET `id_publisher` = NULL, `publisher` = NULL, `artis` = NULL, `id_label` = NULL WHERE `id_publisher` = '113'
this is the code:
function update($id_user=null)
{
if (($this->input->post('submit') == 'Update')){
$user=$this->input->post('username');
$pass=$this->input->post('userpassword');
$ussta=$this->input->post('userstatus');
$usty=$this->input->post('usertype');
$data = array(
'user_name' => $user,
'user_pass' => $pass,
'user_status' => $ussta,
'user_type' => $usty);
$this->db->where('user_id', $this->input->post('id'), $data);
$this->db->update("t_user",$data);
$data1 = array(
'id_publisher' => $id_publis,
'publisher' => $publis,
'artis' => $ar,
'id_label' => $id_lab);
$this->db->where('id_publisher', $this->input->post('id'), $data);
$this->db->update("t_publisher",$data1);
echo $this->db->last_query();
die();
$data2 = array(
'id_label' => $id_lab,
'label' => $label);
$this->db->where('id_label', $this->input->post('id'), $data);
$this->db->update("t_label",$data2);
echo $this->db->last_query();
die();
redirect("registrasi/reg");
}
$var['data'] = $this->db->query("select * from t_user where USER_ID= '$id_user'")->row_array();
$var1['data'] = $this->db->query("select * from t_publisher where id_publisher = '$id_publis'")->row_array();
$var2['data'] = $this->db->query("select * from t_label where id_label = '$id_lab'")->row_array();
$this->load->view('update', $var,$var1,$var2);
}
whats wrong with my code? please help. thanks before.
Your UPDATE clause is setting the id_publisher column to NULL, and, based on the name of the column and the error you're receiving, that column is the table's PRIMARY KEY with a setting of unsigned NOT NULL.
Because of this, when you do id_publisher = NULL, MySQL converts it to id_publisher = 0 due to the unsigned part. This will execute fine the first time, however, when you run it on a second row you will now be attempting to insert a second primary-key value of 0, which is not allowed.
Based on the location of the die() statement in your sample code, I'm assuming the following block is the culprit:
$data1 = array(
'id_publisher' => $id_publis,
'publisher' => $publis,
'artis' => $ar,
'id_label' => $id_lab);
$this->db->where('id_publisher', $this->input->post('id'), $data);
$this->db->update("t_publisher",$data1);
Here, your $id_publis variable is either empty or null.
I would suggest to either remove the id_publisher = NULL portion from the UPDATE clause which is as simple as removing 'id_publisher' => $id_publis, from the $data1 array, or rethink the reason you actually need to set it to null to begin with (in this case, would deleting the row be more beneficial?)

add values with 'on duplicate key'

I have the folowing array called $words
Array
(
[0] => Array
(
[token] => dwA
[pos] => *DII.7,8*
)
[1] => Array
(
[token] => nTr
[pos] => *DI.5,9*
)
[2] => Array
(
[token] => dwA
[pos] => *DI.2,8*
)
[3] => Array
(
[token] => nTr
[pos] => *DI.2,8*
))
I want to insert it with the following :
foreach ($words as $value)
{
$word = $value['token'];
$attestation = $value['pos'];
$insert="INSERT INTO Examples (Word, Attestation) VALUES ('$word', '$attestation')
mysql_query($insert) OR die(mysql_error());
}
The table 'Examples' has a key called ID with auto increasement;
the field word is 'unique'
what I want is that in the field 'Attestation' the values are added each time the 'word' is the same
so the result should be the following:
Id word Attestation
1 dwA *DII.7,8*, *DI.2,8*
2 nTr *DI.5,9*, *DI.2,8*
so I tried to add a 'on duplicate key' phrase
foreach ($words as $value)
{
$word = $value['token'];
$attestation = $value['pos'];
$insert="INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation')
on duplicate key update Attestation =
";
mysql_query($insert) OR die(mysql_error());
}
but I can't figure out what I have to add after Attestation = so that the differents attestations are added one after the other, like for example : DI.5,9, DI.2,8
Or is the 'on duplicate key' not the correct way to do this?
Try this;
INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation')
on duplicate key update Attestation = CONCAT(Attestation, ', ', '$attestation')
Although, it may a bit difficult to break those values apart later on. You may want to consider another table, so you can set up a one-to-many relationship.