Integrity constraints violation? - yii2

$data = (new \yii\db\Query())
->select('categoryMaster_id , categoryMaster_name,categoryMaster_image')
->from('categoryMaster')
->join('LEFT JOIN','productType', 'productType.categoryMaster_id = categoryMaster.categoryMaster_id')
->where('categoryMaster_id=:categoryMaster_id', ['categoryMaster_id' => $_GET['categoryMaster_id']])
->all();
return $data;
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'categoryMaster_id' in where clause is ambiguous\nThe SQL being executed was: SELECT * FROM categoryMaster LEFT JOIN productType ON productType.categoryMaster_id = categoryMaster.categoryMaster_id WHERE categoryMaster_id='1'","code":23000,"type":"yii\db\IntegrityException"

Ambiguous in select. add categoryMaster.categoryMaster_id
$data = (new \yii\db\Query())
->select('categoryMaster.categoryMaster_id, categoryMaster_name, categoryMaster_image')
->from('categoryMaster')
->join('LEFT JOIN','productType', 'productType.categoryMaster_id = categoryMaster.categoryMaster_id')
->where('categoryMaster.categoryMaster_id=:categoryMaster_id', ['categoryMaster_id' => $_GET['categoryMaster_id']])
->all();
return $data;

Related

Yii2 Left Join in query builder

I have two tables, the report_details and the name. In the report_details table, I have for and from which is an id that is related to the table name. What is the proper syntax in Yii2 to get both the for and from the column on the name table? This is my query so far...
$query = new yii\db\Query;
$query->select('report_details.reference_no, report_details.subject, report_details.doc_for, report_details.doc_from, report_details.doc_date, report_details.doc_name, report_details.drawer_id, report_details.user_id, name.name_id, name.position, name.fname, name.mname, name.lname')
->from('report_details')
->join('LEFT JOIN', 'name', 'report_details.doc_for = name.name_id')
->where(['report_details.reference_no' => $model->reference_no]);
$results = $query->all();
you could use ->leftJoin( )
$query = new yii\db\Query;
$query->select('report_details.reference_no, report_details.subject,
report_details.doc_for, report_details.doc_from,
report_details.doc_date, report_details.doc_name,
report_details.drawer_id, report_details.user_id,
name.name_id, name.position, name.fname, name.mname, name.lname')
->from('report_details')
->leftJoin( 'name', 'report_details.doc_for = name.name_id')
->where(['report_details.reference_no' => $model->reference_no]);
$results = $query->all();

Cakephp 3 case sensitive query

$date = date("Y-m-d");
$prev_date = date('m-d-Y', strtotime($date .' -1 day'));
$q = "SELECT `id`, `external_id`, `status`, DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y') as crt, `extras`
FROM `gshuplogs` WHERE DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y') = '$prev_date' and
(BINARY `status` in ('success','DEFERRED') or `status` IS NULL)";
$conn = \Cake\Datasource\ConnectionManager::get('default');
$res = $conn->execute($q)->fetchAll('assoc');
debug($res);exit;
The above query I have written in mysql now I just wanted to write in cakephp 3.
I have tried
$res = $this->Gshuplogs->find()->select([
'id', 'external_id', 'status', 'created'
])->where([
"DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y')" => $prev_date,
'OR' => [
['LOWER status' => 'success'],
['status' => 'DEFERRED'],
['status IS NULL']
]
]);
AND
$res = $this->Gshuplogs->find()->select([
'id', 'external_id', 'status', 'created'
])->where([
"DATE_FORMAT(from_unixtime(`created`),'%m-%d-%Y')" => $prev_date,
'OR' => [
['BINARY status' => 'success'],
['status' => 'DEFERRED'],
['status IS NULL']
]
]);
But it is throwing error.
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'`),'%m-%d-%Y'`) = '06-01-2016' AND (`LOWER` status 'success' OR `status` =
'DEFE' at line 1
Thanks for your response. I got the solution.
$date = date("Y-m-d");
$prev_date = date('m-d-Y', strtotime($date .' -1 day'));
$res = $this->Gshuplogs->find()->select([
'id', 'external_id', 'status', "created"
])->where([
"FROM_UNIXTIME(`created`,'%m-%d-%Y')" => $prev_date,
'OR' => [
['BINARY(status) in ' => ['success','DEFERRED']],
['status IS NULL']
]
]);
debug($res->toArray());exit;

DATEDIFF in YII MYSQL

$criteria = new CDbCriteria();
$criteria->addCondition(array('where' => 'select DATEDIFF(CURDATE(),t.due_date) < 0'));
$dataProvider = new CActiveDataProvider('Loan', array(
'criteria' => $criteria
));
$this->render('index', array(
'dataProvider' => $dataProvider,
));
This is my code, I want to retreive all data from 'Loan' model with some criteria, but I found problem like so:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION libraryng.DATEDIFF does not exist. The SQL statement executed was: SELECT COUNT(*) FROM `loans` `t` WHERE (select DATEFIFF(CURDATE(),t.due_date) < 0)
I hope someone can help me.
change this line to
$criteria->condition('DATEDIFF(CURDATE(),`t`.due_date) < 0');

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

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);

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?)