Database error 1452 - php

I'm working on this project that have foreign keys on two tables. By using a form I'm trying to insert a new record to the database. And there's also an image path in the db and I'm inserting the image path via the form. I'm using codeigniter file upload library. Other fields of the database table get updated when i submit the form even the foreign key field. But the image path is not updating. When I submit the form it shows this error.
A Database Error Occurred
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`bfh`.`products`, CONSTRAINT `category_fk` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`))
INSERT INTO `products` (`img`) VALUES ('assets/img//sakya.PNG')
Filename: C:/xampp/htdocs/CI-skeleton/system/database/DB_driver.php
Line Number: 691
Controller
public function add_product()
{
$result = 0;
$cat_id = $this->input->post("category_id");
$type_id = $this->input->post("type_id");
$pname = $this->input->post("p_name");
$images = $this->input->post("images");
$images = $_FILES['images']['name'];
$price = $this->input->post("price");
$this->load->model("Products_Model");
$product_id = $this->Products_Model->add_product( $cat_id, $type_id, $pname, $price);
if ($product_id != 0) {
$result = $this->Products_Model->add_product_images($images);
}
if ($result && $_FILES['images']['name'][0] != "") {
$this->load->model('Image_Upload');
$result = $this->Image_Upload->upload("assets/img");
}
$this->session->set_flashdata('result', $result);
redirect('Products');
}
Model
public function add_product( $cat_id, $type_id, $pname, $price)
{
$result = $this->db->get_where("products", array('name' => $pname));
if ($result->num_rows() != 0) {
return 0; // record already exists
} else {
$data = array(
'category_id' => $cat_id,
'type_id' => $type_id,
'name' => $pname,
'price' => $price
);
if( !$this->db->insert('products', $data)) {
return -1; // error
}else{
return $this->db->insert_id();
}
return 1; // success
}
}
public function add_product_images($images)
{
$path = "assets/img/";
foreach ($images as $image) {
// if no images were given for the item
if ($image == "") {
return 1;
}
$data = array(
'img' => $path."/".$image
);
if ( ! $this->db->insert('products', $data)) {
return 0; // if something goes wrong
}
}
return 1;
}

You should use "update" query on the behalf of insert in add_product_images().
Because "insert" will add a new record of the product and there is no any category id(Foreign Key) with this that's why shows this error.
So try to update image.

you have two variables with the same name and thats the problem.
You need have different variable name.
I hope this will help you.

there are some problems in this script
if model you wrote, function add product. if your query failed, returns -1 otherwise return product Id
but if product was in database it returns 0, then in controller: you check if product_id != 0 then insert images. so you don't care if product didn't exists in database, you failed you insert that in table or not
in add_product_images you check if ($image == "") . I don't understand how you get that image array ($images) is empty if this statement is true. you can check if (sizeof($images) == 0) before foreach to check emptiness of image array ($images)

Related

How to get imported row id in Laravel Excel

I am using Laravel Excel and I need to get id of imported rows during import.
code
public function model(array $row)
{
$link = new Link([
'site_name' => $row['site_name'],
]);
$name = explode('-', $row['site_name']);
$site = Site::whereIn('name', $name)->pluck('id');
$link->sites()->sync($site, false); // this `$link` can't get id of imported row
return $link;
}
Error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'link_id'
cannot be null (SQL: insert into link_sites (link_id, site_id)
values (?, 14))
Any idea?
Solved
I've changed my function to use onEachRow and it's working now.
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
$row = $row->toArray();
$link = Link::create([
'site_name' => $row['site_name'],
]);
$name = explode('-', $row['site_name']);
$site = Site::whereIn('name', $name)->pluck('id');
$link->sites()->sync($site, false);
}
Document

Multiple Insert with dropdown codeigntier

I have3 table with name frm_data_aset,frm_monitor,frm_lokasi
I want if I insert on frm_data_aset column monitor_aset with dropdown from tabel monitor and lokasi from tabel lokasi. on table monitor column lokasi updated with data same at I insert from tabel data_Aset
this my structure :
enter image description here
enter image description here
now I get error :
Unknown column 'frm_monitor' in 'where clause'
UPDATE frm_monitor SET lokasi_monitor = '123' WHERE frm_monitor IS NULL
this my controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id= $this->input->post('kd_monitor', TRUE);
$data = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data);
$this->M_data_aset->insert($data);
redirect(site_url('data_aset'));
}
}
this my model M_monitor
function update_lokasi($id,$data){
$this->db->where('frm_monitor', $id);
$this->db->update('frm_monitor', $data);
}
and this my dropdown monitor at form insert data_aset
<option value="0">Pilih Monitor</option>
<?php
$monitor = $this->db->get('frm_monitor')->result();
foreach ($monitor as $row){
echo "<option value='$row->kd_monitor' ";
echo $row->kd_monitor==$monitor_aset?'selected':'';
echo ">". strtoupper($row->kd_monitor)."</option>";
}
?>
try changing your model query as like this
function update_lokasi($id,$data){
$this->db->where('id_monitor', $id);
$this->db->update('frm_monitor', $data);
}
Before that make sure that the post for 'kd_monitor' in the controller is not null
You should rename the $data variable being passed to $this->M_monitor->update_lokasi() because it will overwrite $data that is going to be passed to $this->M_data_aset->insert() with only 'lokasi_monitor' array on it. Or even better try rename both $data to prevent confusion.
Modify your controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data_aset = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id = $this->input->post('kd_monitor', TRUE);
$data_monitor = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data_monitor);
$this->M_data_aset->insert($data_aset);
redirect(site_url('data_aset'));
}
}
And change 'frm_monitor' to 'kd_monitor' on the conditional query :
function update_lokasi($id,$data){
$this->db->where('kd_monitor', $id);
$this->db->update('frm_monitor', $data);
}

codeigniter insert many images name into database

I am build uploader images and store it into database, I already can upload many images to folder, but I can't insert all images name that uploaded, and I don't know how to insert into database, first I have put commend on my code below when error occur, second I don't know the query to put it in database if the image count is different e.g 1-10 images, last question, if I do query "SELECT id..." and I want to return it, is there method to return it into string or int? If I use row() it will return stdClass object. please help me,
below is my code:
controller :
$this->load->library("myupload", "form_validation");
$this->load->model("testModel");
$barangImage = array();
if($this->input->post("formSubmit")) {
$this->form_validation->set_rules("nama", "Nama", "required|trim");
if($this->form_validation->run()) {
$insertData = array(
"nama" => $this->input->post("nama")
);
if($id = $this->testModel->add($insertData)) {
//print_r($id);
if(isset($_FILES) && $image = $this->myupload->uploadFile($_FILES)) {
//$image here is already fill with all images name
if(isset($image["error"]) && $image["error"]) {
echo $image["error"];
}else {
foreach($image as $img) {
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
//but when i put into barangImage,
//it only stored last image name
print_r($barangImage);
//output `Array ( [gambar] => 2.JPG [barangid] => Array ( [id] => 52 ) )`
}
}
if($id = $this->testModel->add_images($barangImage)) {
echo "SUCCESS !!!";
}else {
echo "FAIL INSERT IMAGES!!!";
}
}else {
echo "FAIL INSERT DATA NAMA";
}
}else {
echo "FAIL VALIDASI RUN";
}
}
model :
public function add($newData){
$this->db->insert("cobabarang", $newData);
$nama = $newData["nama"];
$id = $this->db->query("SELECT id FROM cobabarang WHERE nama = \"$nama\"");
return $id->row_array();
}
public function add_images($newImage) {
//$this->db->insert("cobagambar", $newImage);
$id = $newImage["barangid"]["id"];
$gambar = $newImage["gambar"];
$this->db->query("INSERT INTO cobagambar(barangid, gambar1) VALUES($id, \"$gambar\")");
}
there is an error here:
foreach($image as $img)
{
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
change the $barangImage to $barangImage[]
when you put the images into database i suggest that using json_encode($barangImage), and then json_decode($images-json-string) when you going to use the images.
There is something wrong with your foreach loop
foreach($image as $img) {
$barangImage = array(
"gambar" => $img //might be img['img'] I guess $img is again an array...you hvae to check that
"barangid" => $id //might be $img['id']check on this too..will be $img['id'] I guess
);
}
My guess is that $img is again an array with some keys. You really need to check on that And you can directly call the insert function in that foreach loop itself like this,
foreach($image as $img) {
$barangImage = array(
"gambar1" => $img['img'], //I guess $img is again an array...you hvae to check that
"barangid" => $img['id'] //check on this too..will be $img['id'] I guess
);
$id = $this->testModel->add_images($barangImage));
}
NOTE: The keys in your array barangImage must be column name in the table. i.e
gambar1 and barangid will be your column names. so you can directly use codeIgniter's active records.
Just change your add_images function
public function add_images($newImage) {
$this->db->insert("cobagambar", $newImage);
}

magento Integrity Constraint Violation during product creation/update

I'm currently trying to integrate magento into an ERP System using an self written middleware.
I get this message:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`magento`.`catalog_product_entity`, CONSTRAINT `FK_CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`a)
I don't really know where the problem lies.
The result Object of a Product get and Product write look similar.
I checked the web already for help, but couldn't find an solution for it.
I also don't really know where to search, because the message on top is the only one I get.
Any help is appreceated.
Well the code itself is split up into multiple sections
but I'll try to show as much as possible
$this->product = Mage::getModel('catalog/product')->loadByAttribute('sku',$this->handler['art_nr']);
if($this->product===false || $this->product->getId()<1){
$this->product = Mage::getModel('catalog/product');
$this->product->setSku($this->handler['art_nr']);
$this->newProduct = true;
}
$this->product->setStatus($this->shoparticle['products_status']);
$this->product->setName($this->handler['art_name']);
$categories = array();
if(!$this->isNewProduct()){
$categories = $this->product->getCategoryIds();
}
$categories = $this->handler['all_categories'];
$this->product->setCategoryIds($categories);
$crosssellingSet = array();
$upsellingSet = array();
$relatedSet = array();
if(is_array($this->handler['xselling']) && count($this->handler['xselling'])>0){
foreach($this->handler['xselling'] as $valueSet){
$product = Mage::getModel('catalog/product')->loadBySku($valueSet['art_nr']);
if((int)$valueSet['group']===1){
$crossselling[$product->getId()] = array('position'=>$valueSet['sort_oder']);
}else if((int)$valueSet['group']===2){
$upsellingSet[$product->getId()] = array('position'=>$valueSet['sort_oder']);
}else if((int)$valueSet['group']===3){
$relatedSet[$product->getId()] = array('position'=>$valueSet['sort_oder']);
}
}
}
$this->product->setCrossSellProductsData($crosssellingSet);
$this->product->setUpsellingProductsData($upsellingSet);
$this->product->setRelatedProductsData($relatedSet);
$importDir = Mage::getBaseDir('media') . DS . 'import' . DS;
//check if exists and add .htaccess file for protection
if(!is_dir($importDir)){
#mkdir($importDir,0775,true);
#chmod($importDir,0775);
}
if(!is_dir($importDir)){
throw new Connector_Model_Exception_Error('Could not create import Directory!');
}
if(!file_exists($importDir.'.htaccess')){
file_put_contents($importDir.'.htaccess','Order deny,allow'."\n".'Deny from all'."\n");
}
//clean direcotry
$dir = dir($importDir);
while(($e=$dir->read())!==false){
if(strpos($e,'.jpg')||strpos($e,'.png')||strpos($e,'.jepg')||strpos($e,'.gif')||strpos($e,'.tif')){
#unlink($importDir.$e);
}
}
//write images into directory
//and run Import
foreach($this->handler['images'] as $image){
file_put_contents($importDir.$image['image_name'],$image['image']);
$this->product->addImageToMediaGallery($importDir.$image['image_name'], array('image', 'small_image', 'thumbnail'), false, false);
}
$groups = Mage::getModel('customer/group')->getCollection()->getAllIds();
if((float)$this->handler['Bpreis'] > 0.00){
$this->product->setPrice((float)$this->handler['Bpreis']);
}
if((float)$this->handler['art']['products_pprices'] > 0.00){
$this->product->setMsrp((float)$this->handler['art']['products_pprices']);
}
//preapre the price data for ranges
$groupsets = array();
if(count($this->handler['PGROUP'])){
foreach($this->handler['PGROUP'] as $group){
if(in_array(((int)$group['gruppe']-250),$groups)){
$groupsets[((int)$group['gruppe']-250)][(float)$group['marge']] = (float)$group['PGPRICE'];
}
}
}
//Now run ageanst groupsets to set price range etc
$storeid = Mage::app()->getStore()->getWebsiteId();
foreach($groupsets as $groupid=>$rangeset){
if(count($rangeset)>0){
foreach($rangeset as $key=>$value){
if(count($rangeset)===1 && $key === (float)0){
$this->product->setData(
'group_price',
array(
'website_id'=>$storeid,
'cust_group'=>$groupid,
'price'=>$value,
)
);
}else{
$this->product->setData(
'tier_price',array(
'website_id'=>$storeid,
'cust_group'=>$groupid,
'price'=>$value,
'price_qty'=>$key
)
);
}
}
}
}
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
if($this->isNewProduct()){
$this->product->setCreatedAt(strtotime('now'));
}
$this->product->save();
The error is telling you exactly what the problem is. You are trying to save a product with an incorrect attribute set id. By that it means that the attribute set id you have set or not set in this case is not in the eav_attribute_set table. I think it's because if you create a new product you are not setting it. If you are updating an existing one you dont need to set it.
if($this->product===false || $this->product->getId()<1){
$this->product = Mage::getModel('catalog/product');
$this->product->setSku($this->handler['art_nr']);
// Set Attribute Set. Should be numeric for simple, bundle, configurable, grouped etc
$this->product->setAttributeSetId($this->handler['art_attribute_set_id']);
$this->newProduct = true;
}
Please check are you using right Attribute set id with your code. Please share the code where you have written the code to update/save the product.

Cakephp update or add new record

I have an image upload that adds the filename to a table called attachments. If the id already exists then I want it to update and if not then create a new record. At the moment it creates a new record so I have multiple records forthe one id. The id's are from a table called Addon's.
I am not sure how to do this in cakephp.
if (!empty($this->data)) {
$this->layout = null;
//if(empty($this->data['AddOn']['id'])){unset($this->data['AddOn']);}
// restructure data for uploader plugin // NEED TO GET RID OF THIS ? MOVE IT
$tmp_file = $this->data['Attachment'][0]['file'];
$tmp_file['extension'] = array_reverse(explode('.', $tmp_file['name']));
$tmp_file['extension'] = $tmp_file['extension'][0];
$tmp_file['title'] = strtolower(substr($tmp_file['name'],0,(0-strlen('.'.$tmp_file['extension']))));
$this->data['Attachment'][0]['alternative'] = ucwords(str_replace('_',' ', $tmp_file['title']));
$previous = $this->AddOn->Attachment->find('first', array('conditions'=> array('model'=>'AddOn', 'foreign_key'=>$id)));
if( !empty( $previous ) ) {
$this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
}
if ($this->AddOn->save($this->data, array('validate' => 'first'))) {
$id = $this->AddOn->Attachment->getLastInsertID();
$att = $this->AddOn->Attachment->query("SELECT * from attachments WHERE id = ".$id);
$this->set('attachment',$att[0]['attachments']);
} else {
$tmp_file['name'] = 'INVALID FILE TYPE';
}
//debug($this->data);
$this->set('file', $tmp_file);
$this->RequestHandler->renderAs($this, 'ajax');
$this->render('../elements/ajax');
}
save() and saveAll() automatically update an existing row if the id has been set. You can do something like:
$previous = $this->AddOn->Attachment->find( /* whatever conditions you need */ );
if( !empty( $previous ) ) {
$this->AddOn->Attachment->id = $previous[ 'Attachment' ][ 'id' ];
}
Now the old record will be updated if it exists.
As a side note, the code after a successful saveAll() doesn't make much sense: first you're saving data to the database, then immediately retrieving it again. You can just keep using $this->data that already has the same content.
And another side note: you should use query() only as a last resort when you can't use Cake's other methods. query("SELECT * from attachments WHERE id = ".$id) is a trivial case that can be rewritten as $this->Model->id = $id; $this->Model->read(); or using a simple $this->Model->find() query.

Categories