I want to update one field in my db. I have the below query, but I am getting error in this.
$list = Test::model()->find(array(
'select'=>'name',
'condition'=>'id=:id AND name=:name AND provider="fb"',
'params'=>array(
':id'=>Yii::app()->user->id,
':name'=> $name,
),
));
$list->name = $user_name[$k]['name'];
if($list->save())
{
echo "done";exit;
}
else
{
$error = $list->getErrors();
var_dump($error);exit;
}
Error:
'Column name must be either a string or an array
This happens when you don't have a primary key in your table and you try to save some data in table. check if you have set primary key and it set properly. more details
Related
this is my code for updating:
PS: empid is a foreign key but i think that shouldnt be the reason and the code is in CakePHP
if($this->request->is('post'))
{
$this->request->data["Leave"]["empid"] = $this->request->data["id"];
$this->Leave->empid = $this->request->data["Leave"]["empid"];
$this->request->data["Leave"]["leave_start"] = $this->request->data["start_date"];
$this->request->data["Leave"]["leave_end"] = $this->request->data["end_date"];
$this->request->data["Leave"]["leave_taken"] = $this->request->data["leave_taken"];
if($this->Leave->save($this->request->data['Leave']))
{
return $this->redirect(array('action' => 'manage_leave'));
}
}
// This code is inserting a new row instead of updating and also not adding any value in the new row
May be your trying to update the foreign table data using simple save.
Update multiple records for foreign key
Model::updateAll(array $fields, mixed $conditions)
Example
$this->Ticket->updateAll(
array('Ticket.status' => "'closed'"),
array('Ticket.customer_id' => 453)
);
Simple save for the primary key
Make sure that your HTML has empid
echo $this->Form->input('Leave.empid', array('type' => 'hidden'));
Save Model
$this->Leave->empid = $this->request->data["Leave"]["empid"]; //2
$this->Leave->save($this->request->data);
In between, you can also try to set the model data and check the $this->Leave->validates() and $this->Leave->validationError if they are giving any validation errors.
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);
// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
You can find more information about all Saving your data
Hope this helps you :)
And in case if $empid is primary key of corresponding table of Leave model (e.g leaves), Just replace:
$this->Leave->empid = $this->request->data["Leave"]["empid"];
By
$this->Leave->id = $this->request->data["Leave"]["empid"];
I need to insert some values to custom database table based on the values of changed custom field, if the specific custom field value (in a custom shipping method) had changed.I need to check this in my Observer.php event that I'm firing is admin_system_config_changed_section_carriers for getting values from the field and insert values to the table
is there any possible way to do this ?
EDIT:
here is my observer function
public function handle_adminSystemConfigChangedSection($observer){
$post = Mage::app()->getRequest()->getPost();
$firstBarcodeFlatrate = $post['groups']['flatrate']['fields']['barcode_start']['value'];
$lastBarcodeFlatrate = $post['groups']['flatrate']['fields']['barcode_end']['value'];
$flatrateRange = range($firstBarcodeFlatrate,$lastBarcodeFlatrate);
$shippingMethod = 'flatrate';
foreach($flatrateRange as $barcodes){
$insertData = array(
'barcode' => $barcodes,'shipping_method' => $shippingMethod,'status' => 1,
);
$model = Mage::getModel('customshippingmethods/customshippingmethods')->setData($insertData);
try {
$model->save();
} catch (Exception $e){
echo $e->getMessage();
}
}
as you can see above database query will update each time I save the configuration but I just need to run the query iff $firstBarcodeFlatrate value had changed
I would probably go with two options:
1. Cache the last value of $firstBarcodeFlatrate
$cacheId = 'first_barcode_flatrate_last_value';
$cache = Mage::app()->getCache();
$lastValue = $cache->load($cacheId);
if (!$lastValue) {
//We don't have cached last value, we need to run the query and cache it:
//Cache the value:
$cache->save($firstBarcodeFlatrate, $cacheId, array('first_barcode_flatrate_last_value'), null);
//Run the query here
} else {
//We have last value, we need to check if it has been changed:
if($lastValue != $firstBarcodeFlatrate) {
//Update the cached value:
$cache->save($firstBarcodeFlatrate, $cacheId, array('first_barcode_flatrate_last_value'), null);
//Run the query here.
}
}
Option 2 is to create another table with a single row and two fields or add another system config field that will store the last used value. Then before the running the query, you will check this value if it's different than $firstBarcodeFlatrate you will run the query, otherwise you won't, though I think the caching will do the job for you.
I have this function to update a record, but i cannot it fails and send me a "Primary key ID missing from row or is null" message, how can I fix it?
public static function update_child($data)
{
try
{
$update= ORM::for_table("dm_child",DM_TAG)
->where_equal($data["id_child"]);
$update -> set(array(
"gender" => $data["gender"]
"age_year" =>$data["year"]
"age_month" => $data["month"]
));
$update -> save();
}
catch(PDOException $ex)
{
ORM::get_db()->rollBack();
throw $ex;
}
}
Idiorm assumes that the name of the primary key is 'id', which is not that, in your case.
Therefore you have to explicitly specify it to Idiorm:
<?php
ORM::configure('id_column_overrides', array(
'dm_child' => 'id_child',
'other_table' => 'id_table',
));
See Docs>Configuration.
The answer is indeed the one provided by #iNpwd for changing the default 'id' column name for queries on a per table basis:
ORM::configure('id_column_overrides', array(
'table_name' => 'column_name_used_as_id',
'other_table' => array('pk_1', 'pk_2') // a compound primary key
));
The thing that was biting me on getting it to recognize my query was WHERE I was changing the ORM::configure values. I was not in the correct file.
A deeper link to specifically the ID Column configuration: http://idiorm.readthedocs.org/en/latest/configuration.html#id-column
I just met this problem 2 minutes ago. The real reason is, you forgot select id field in querying.
demo:
$demo = ORM::for_table('demo')->select('field_test')->find_one($id);
$demo->field_test = 'do';
$demo->save();
You will get the error.
change to :
$demo = ORM::for_table('demo')->select('field_test')->select('id')->find_one($id);
It will fix the problem.
Some tips in documents:
https://github.com/j4mie/idiorm/blob/master/test/ORMTest.php
/**
* These next two tests are needed because if you have select()ed some fields,
* but not the primary key, then the primary key is not available for the
* update/delete query - see issue #203.
* We need to change the primary key here to something other than id
* becuase MockPDOStatement->fetch() always returns an id.
*/
I've never used idiorm, so cannot guarantee that my answer will work for you, but from this page and under "Updating records", we have an example which is similar but slightly different to yours.
// The 5 means the value of 5 in the primary-key column
$person = ORM::for_table('person')->find_one(5);
// The following two forms are equivalent
$person->set('name', 'Bob Smith');
$person->age = 20;
// This is equivalent to the above two assignments
$person->set(array(
'name' => 'Bob Smith',
'age' => 20
));
// Syncronise the object with the database
$person->save();
I'm sure I'll learn the reason behind this, but let me tell you all I understand at the moment, and how I "fixed" it.
Here is the beginning of idiorm's save function:
public function save() {
$query = array();
// remove any expression fields as they are already baked into the query
$values = array_values(array_diff_key($this->_dirty_fields, $this->_expr_fields));
if (!$this->_is_new) { // UPDATE
// If there are no dirty values, do nothing
if (empty($values) && empty($this->_expr_fields)) {
return true;
}
$query = $this->_build_update();
$id = $this->id(true);
Right there, on that last line, when trying to access the $this->id, you are getting an exception thrown:
throw new Exception('Primary key ID missing from row or is null');
$this does not contain an id property. I'm not really sure how it could. The example given both on their homepage and in the docs doesn't do anything special to address this. In fact I am copying them 1:1 and still yielding the same error as you.
So, all that said, I fixed this error by just adding in my own id:
$crop = ORM::for_table('SCS_Crop')->find_one($id);
$crop->id = $id;
$crop->Name = "Foo";
$crop->save();
This also happens when the id field name is ambiguous, e.g. when joining two tables both having an id column. This is the case with referenced tables
Model::factory('tableOne')
->left_outer_join('tableTwo', array('tableOne.tableTwo_id', '=', 'tableTwo.id'))
->find_one($id);
In these cases set an alias to the ID column of the parent tableOne to later access it while saving. Make sure that you also select other columns you need - e.g. by ->select('*'):
Model::factory('tableOne')
->select('*')
->select('tableOne.id', 'id')
->left_outer_join('tableTwo', array('tableOne.tableTwo_id', '=', 'tableTwo.id'))
->find_one($id);
if in table primary key/ field name not id then following id column overrides required
default id (primary_key) to replace with other id name (primary_key)
ORM::configure('id_column_overrides', array(
'user' => 'user_id',
));
$update = ORM::for_table('user')->find_one(1);
$update->name = "dev";
try{
$update->save();
}catch(Exception $e){
echo $e;
}
print_r($update);
I am having a form with an appending table which goes on appending the values entered in the form to the table and as I click the Save button, the entire record set goes to the table...
The Controller page:-
function invoiceEntry(){
$ref_invoice_no=$_POST['ref_invoice_no'];
$entry_date=$_POST['entry_date'];
$store_name=$_POST['store_name'];
$store_name=empty($_POST['store_name']) ? NULL : $_POST['store_name'];
$no_packages=$_POST['no_packages'];
$net_weight_each=$_POST['net_weight_each'];
$total_net_qty=$_POST['total_net_qty'];
$obj=new Sales();
foreach ($ref_invoice_no as $key => $value) {
$obj->addInvoice($ref_invoice_no[$key],$entry_date[$key],$store_name[$key],$no_packages[$key],$net_weight_each[$key],$total_net_qty[$key]);
}
}
The Model page:-
function addInvoice($ref_invoice_no,$fregno,$entry_date,$catalogue_type,$store_name,$category,$grade,$pack_type,$manufacture_date,$full_half,$sample_allowed,$no_packages,$net_weight_each,$total_net_qty){
$conn=new Connection();
$sql="INSERT INTO invoice (ref_invoice_no,fac_reg_no,date_of_entry,exestate_mainsale,stores_code,category_code,grade_code,packing_code,date_of_manufacture,full_half,sample_allowed,no_of_packages,net_weight_each,total_net_qty) VALUES('$ref_invoice_no','$fregno','$entry_date','$catalogue_type',$store_name,'$category','$grade','$pack_type','$manufacture_date','$full_half','$sample_allowed','$no_packages','$net_weight_each','$total_net_qty')";
echo $sql;
$result=$conn->query($sql);
return $result;
}
I am getting the error as :-
Cannot add or update a child row: a foreign key constraint fails (teabs.invoice, CONSTRAINT invoice_ibfk_2 FOREIGN KEY (stores_code) REFERENCES stores (stores_code))
But if I go and place the query in PHPMyAdmin, it works perfectly as I have set the stores field to accept NULL values.
This is wrong since store_name is an array, and u need to check the indexes. this code is never setting null.
$store_name=empty($_POST['store_name']) ? NULL : $_POST['store_name'];
change it to:
$store_name=$_POST['store_name'];
You need to move that logic into:
$obj->addInvoice($ref_invoice_no[$key],$entry_date[$key],empty($store_name[$key]) ? NULL : $store_name[$key],$no_packages[$key],$net_weight_each[$key],$total_net_qty[$key]);
You can check if this works.
I am using HMVC. My question is very simple. how we can catch the error in active records?
how we can return custom error to controller from model(active records)?
Actually, msn column is unique so, when i enter duplicate value then its show error like
Error Number: 1062
Duplicate entry '3696003284' for key 'msn'
but i want to show custom error instead of this.
my simple code is:
function insert_data($msn_number, $date_val, $min_val, $max_val, $avg_val,$counter)
{
for($i=0;$i<$counter;$i++)
{
$data = array(
'msn' => $msn_number[$i],
'date' => $date_val[$i],
'min_val' => $min_val[$i],
'max_val' => $max_val[$i],
'average' => $avg_val[$i]
);
$result = $this->db->insert('storage_data', $data);
if(!isset($result))
{
echo "custom Error";
}
}
}
}
i am wondering for the answer of this question please help me!
You may try this:
$result = $this->db->insert('storage_data', $data);
if (!$result) {
$data['msg'] = $this->db->_error_message();
$this->load->view('viw_db_error', $data); // Create a viw_db_error.php view
}
Make sure DB_DEBUG is set to FALSE in the application/config/database.php file, or execution will be halted if a mysql error occurs.
Update:
Alternatively you may query for that before every time you insert a new record but it would be very expensive because you are doing it inside a loop and it'll send many query/requests:
$q = $this->db->query("select msn from storage_data where msn = $msn_number[$i]");
if( $q->num_rows() ) {
// It already exists so maybe display a message
}