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?)
Related
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.
I want execute this query like
UPDATE `eventinfo` SET `Status` = '0' WHERE `EventDatetime`< `2015-05-12 01:17:23`.
I tried it in different ways like this
$whereClause = 'EventDatetime'.'<'.$check_date;
$this->db->where($whereClause);
but I failed.What is the correct way.
Different way to do this :
$data = array( 'status' => '0', );
$this->db->where('EventDatetime <', '2015-05-12 01:17:23');
$this->db->update('eventinfo', $data);
Using codeigniter way for less then and greater then
$this->db->set('Status',0);
$this->db->where('EventDatetime <', '2015-05-12 01:17:23');
$this->db->update('eventinfo');
You need quotes around dates in that format.
UPDATE `eventinfo`
SET `Status` = '0'
WHERE `EventDatetime`< '2015-05-12 01:17:23'
;
This is how you can do it
$data = array( 'Status' => '0', );
$this->db->where('EventDatetime <', '2015-05-12 01:17:23');
$this->db->update('eventinfo', $data);
NOTE:
Note the space between 'EventDatetime' and '<', if there is no space, you will get an error
there are many ways to do so
$data = array( 'status' => '0', );
$whereClass="eventdatetime < '2015-05-12 01:17:23'";
$this->db->where($whereClass,NULL,FALSE);
//or $this->db->where('eventdatetime < ' ,'2015-05-12 01:17:23');
$this->db->update('eventinfo', $data);
if still got error then there must database error ,may be a missing record or something
I have an insert query (active record style) used to insert the form fields into a MySQL table. I want to get the last auto-incremented id for the insert operation as the return value of my query but I have some problems with it.
Inside the controller:
function add_post(){
$post_data = array(
'id' => '',
'user_id' => '11330',
'content' => $this->input->post('poster_textarea'),
'date_time' => date("Y-m-d H:i:s"),
'status' => '1'
);
return $this->blog_model->add_post($post_data);
}
And inside model:
function add_post($post_data){
$this->db->trans_start();
$this->db->insert('posts',$post_data);
$this->db->trans_complete();
return $this->db->insert_id();
}
I get nothing as the return of the add_post in model
Try this
function add_post($post_data){
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
In case of multiple inserts you could use
$this->db->trans_start();
$this->db->trans_complete();
A transaction isn't needed here, this should suffice:
function add_post($post_data) {
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
$id = $this->db->insert_id();
From the documentation:
$this->db->insert_id()
The insert ID number when performing database inserts.
Therefore, you could use something like this:
$lastid = $this->db->insert_id();
Using the mysqli PHP driver, you can't get the insert_id after you commit.
The real solution is this:
function add_post($post_data){
$this->db->trans_begin();
$this->db->insert('posts',$post_data);
$item_id = $this->db->insert_id();
if( $this->db->trans_status() === FALSE )
{
$this->db->trans_rollback();
return( 0 );
}
else
{
$this->db->trans_commit();
return( $item_id );
}
}
Source for code structure: https://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually
It is worth saying that the other answers relate to Codeigniter version 3. The answer in Version 4 (found https://codeigniter.com/user_guide/database/helpers.html) is to use $this->db->insertID()
because you have initiated the Transaction over the data insertion so,
The first check the transaction completed or not. once you start the transaction, it should be committed or rollback according to the status of the transaction;
function add_post($post_data){
$this->db->trans_begin()
$this->db->insert('posts',$post_data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
$this->db->trans_rollback();
return 0;
}else{
$this->db->trans_commit();
return $this->db->insert_id();
}
}``
in the above, we have committed the data on the successful transaction even you get the timestamp
Just to complete this topic:
If you set up your table with primary key and auto increment you can omit the process of manually incrementing the id.
Check out this example
if (!$CI->db->table_exists(db_prefix() . 'my_table_name')) {
$CI->db->query('CREATE TABLE `' . db_prefix() . "my_table_name` (
`serviceid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`hash` varchar(32) NOT NULL,
`url` varchar(120) NOT NULL,
`datecreated` datetime NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');
Now you can insert rows
$this->db->insert(db_prefix(). 'my_table_name', [
'name' => $data['name'],
'hash' => app_generate_hash(),
'url' => $data['url'],
'datecreated' => date('Y-m-d H:i:s'),
'active' => $data['active']
]);
**Inside Model**
function add_info($data){
$this->db->insert('tbl_user_info',$data);
$last_id = $this->db->insert_id();
return $last_id;
}
**Inside Controller**
public function save_user_record() {
$insertId = $this->welcome_model->save_user_info($data);
echo $insertId->id;
}
You must use $lastId = $this->db->insert_id();
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);
I'm using MDB2 for prepared statements. I'm using the name-based example from the PEAR MDB2 site as a guide, and this is what I have so far:
$q = '
UPDATE
abc_news
SET
newstitle = :newstitle,
categoryid = :categoryid,
facilityid = :facilityid,
user_id_mod = :user_id_mod,
user_id_add = :user_id_add,
display = :display,
locked = :locked,
datemodified = NOW()
WHERE
newsid = :newsid
';
$types = array(
'text',
'integer',
'integer',
'integer',
'integer',
'integer',
'integer',
'integer',
);
$res = $mdb2_dbx->prepare($q, $types,MDB2_PREPARE_MANIP);
$data = array(
'newstitle' => $n_newstitle,
'categoryid' => $n_categoryid,
'facilityid' => $n_facilityid,
'display' => 1,
'locked' => 1,
'user_id_add' => $n_user_id_add,
'user_id_mod' => $n_user_id_mod,
'newsid' => $newsid,
);
$affected_rows = $statment->execute($data);
if (PEAR::isError($res))
die('error');
$statement->free();
$q = '
UPDATE
abc_news_text
SET
newstext = :newstext
WHERE
newsid = :newsid
';
$types = array(
'text',
'integer',
);
$statment = $mdb2_dbx->prepare($q, $types,MDB2_PREPARE_MANIP);
$data = array(
'newstext' => $n_newstext,
'newsid' => $newsid,
);
$affected_rows = $statment->execute($data);
if (PEAR::isError($res))
die('error');
$statement->free();
The first query works - an autoincremented $newsid is printed to the screen (it increases with each new submission).
Directly below, I get this error:
Fatal error: Call to undefined method MDB2_Error::execute() in news.php on line 160
Line 160 is the second $affected_rows = $statment->execute($data); line.
I'm freeing up the statement, and the syntax appears to be the same on both prepared statements.
What am I doing wrong here?
that is because You are getting an MDB2_ERROR object not a statement object. Your prepare() obviously didn't work and you are not checking for the success of the prepare() at all to know this.
Also, I am not sure how your first is working since you set the prepare result to $res variable instead of $statment. I also notice your variable name $statment has no e (not sure if this was a typo).