When I update the data in the database using the form below, the error following error is shown. How can I solve this error?
Cannot add or update a child row: a foreign key constraint fails
(`nov-cms`.`faqs_cat`, CONSTRAINT `faqs_cat_ibfk_20` FOREIGN KEY (`id`)
REFERENCES `tblfaqs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)'
Form:
function editpage_($editid) {
$conn = Doctrine_Manager::connection();
$data['headingtop'] = "FAQ'S > FAQ'S > Edit FAQ'S";
$data['title_faqs'] = "Edit FAQ's";
$data['errormess'] = '';
$title_faqs = addslashes($this->input->post('title_faqs'));
$content = addslashes($this->input->post('editor1'));
$seo_description = addslashes($this->input->post('seo_description'));
$category = $this->input->post('category'); //print_r($category['cate']); exit;
$isActive = $this->input->post('isactive');
$position = $this->input->post('position');
$qryDel2 = $conn->prepare("DELETE from faqs_cat where id='$editid'");
$qryDel2->execute();
$query = $conn->prepare("UPDATE tblfaqs SET title_faqs='$title_faqs',content='$content',isActive='$isActive',position='$position',seo_description='$seo_description' WHERE id='$editid' ");
$query->execute();
$id = $conn->lastInsertId();
//when we add a page this insert a record to table, and this is id of record inserted.. this is a function default of mysql, we use to get last insert id to insert this to orther table...
foreach ($category as $data) {
$query = $conn->prepare("insert into faqs_cat (fc_id, id, category_id) values ('','$id','$data')"); //in this.
$query->execute();
}
$url = 'admin/faqs/';
echo'
<script>
window.location.href = "' . base_url() . $url . '";
</script>
';
The error is in this line:
$id = $conn->lastInsertId();
Specifically, $id remains empty because lastInsertId() is not returning a value. This causes the constraint to fail because when inserting into faqs_cat an ID is required.
If you're trying to get an auto-generated key from the database, you may need to specify a sequence name to lastInsertId depending on what type of database you're connecting to (for example, Postgres requires a sequence name). Try creating a sequence called 'mySequence' and using this instead:
$id = $conn->lastInsertId('mySequence');
Related
hello i want to update the row by clicking on edit button, but it giving me this error, kindly help
function updateUser()
{
$data = stripslashes(file_get_contents("php://input"));
$mydata = json_decode($data, true);
$id = $mydata['sid'];
//retrieve specific info
$sql = "SELECT * FROM admin WHERE id = {$id}";
$result = $this->db->query($sql);
$row = $result->fetch_assoc();
echo json_encode($row); //returning json formate
}
Use $result->row_array(); instead of $result->fetch_assoc();
To prevent sql injection, you may also want to bind the $id separately instead of concatenating it into the query, like this:
$sql = "SELECT * FROM admin WHERE id = ?";
$result = $this->db->query($sql, array($id));
$row = $result->row_array();
See also: https://codeigniter.com/userguide3/database/queries.html#query-bindings
This code above adds data to the database but it does not update if the data already exsists.
public function updateStudentPastoral(){
// Getting all post data
$data = Input::all();
$pCollection = new PastoralCollection();
$pCollection->fill($data);
$response = '';
if ($pCollection->save())
$response = 'success';
else
$response = 'error';
return (json_encode($response));
}
i want to check if the data already exists so i will update it in the database but if it does exist it will save in the database.
You can use the laravel firstOrnew method like so:
$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save();
This will check if there is a record matching name if there is it will be updated otherwise a new one will be createad.
How to use:
JFactory::getDbo()->insertObject('#__card_bonus', $object);
with on duplicate key update ?
You have a few options:
1) Check for an entity id. This is my preferred option, because it only uses a single query, is reusable for any object, and is database agnostic - meaning it will work on whichever DBMS you choose, whereas the other two options are exclusive to MySQL.
if (isset($object->id)) {
$db->updateObject('#__card_bonus', $object);
}
else {
$db->insertObject('#__card_bonus', $object, 'id');
}
I often create an abstract model with a save(stdClass $object) method that does this check so I don't have to duplicate it.
2) Write your own query using the MySQL ON DUPLICATE KEY UPDATE syntax, which is a proprietary extension to the SQL standard, that you have demonstrated understanding of.
3) Write your own query using MySQL's proprietary REPLACE INTO extension.
<?php
$jarticle = new stdClass();
$jarticle->id = 1544;
$jarticle->title = 'New article';
$jarticle->alias = JFilterOutput::stringURLSafe($jarticle->title);
$jarticle->introtext = '<p>re</p>';
$jarticle->state = 1;
$jarticle->catid = 13;
$jarticle->created_by = 111;
$jarticle->access = 1;
$jarticle->language = '*';
$db = JFactory::getDbo();
try {
$query = $db->getQuery(true);
$result = JFactory::getDbo()->insertObject('#__content', $jarticle);
}
catch (Exception $e){
$result = JFactory::getDbo()->updateObject('#__content', $jarticle, 'id');
}
I use this method - are not fully satisfied, but ...
or for not object method:
$query = $db->getQuery(true);
$columns = array('username', 'password');
$values = array($db->quote($username), $db->quote($password));
$query
->insert($db->quoteName('#__db_name'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$query .= ' ON DUPLICATE KEY UPDATE ' . $db->quoteName('password') . ' = ' . $db->quote($password);
$db->setQuery($query);
JFactory::getDbo()->insertObject('#__card_bonus', $object, $keyName);
The name of the primary key. If provided the object property is updated.
Joomla doc ...
I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.
Is there an admin tool in Magento which will remove all images from all products? I know you can go product-by-product and remove all images, but I'm wondering if there's an admin tool which will do all products at once?
Thanks in advance.
I am not sure why you would like to do this but here is a way to do it directly from the Database.
Backup then truncate these 2 tables:
catalog_product_entity_media_gallery
catalog_product_entity_media_gallery_value
then delete '/media/catalog/product'
clear all caches.
I haven't tested it but it should do the job. If it doesnt work then restore those 2 tables
This method is tested and does work. One reason you might want to do this is when you're testing Dataflow Import for products. When you specify images in the upload, Magento only adds images - it doesn't replace or remove them.
The net result is that several runs of a profile will accumulate a number of images that are superfluous.
mysql> **truncate catalog_product_entity_media_gallery;**
mysql> **truncate catalog_product_entity_media_gallery_value;**
Then, from the command prompt of your Magento media/catalog folder:
media/catalog$ **rm -rf ./product/**
It is a bad idea to do this via the DB, but if you must:
ALTER TABLE `catalog_product_entity_media_gallery_value`
DROP FOREIGN KEY `FK_CAT_PRD_ENTT_MDA_GLR_VAL_STORE_ID_CORE_STORE_STORE_ID`,
DROP FOREIGN KEY `FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID`;
TRUNCATE `catalog_product_entity_media_gallery_value`;
TRUNCATE `catalog_product_entity_media_gallery`;
ALTER TABLE `catalog_product_entity_media_gallery_value`
ADD CONSTRAINT `FK_CAT_PRD_ENTT_MDA_GLR_VAL_STORE_ID_CORE_STORE_STORE_ID` FOREIGN KEY (`store_id`) REFERENCES `core_store` (`store_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID` FOREIGN KEY (`value_id`) REFERENCES `catalog_product_entity_media_gallery` (`value_id`) ON DELETE CASCADE ON UPDATE CASCADE;
Then you can delete the product folders with:
cd media/catalog/product
rm -rf *
That's how I fixed it:
public function __construct(
\Magento\Catalog\Model\Product $product,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Model\Product\Gallery\Processor $processor
) {
$this->productRepository = $productRepository;
$this->product = $product;
$this->resource = $resource;
$this->processor = $processor;
}
protected function removeImageGallery($product)
{
try {
$gallery = $this->resource->getTableName('catalog_product_entity_media_gallery');
$galleryValue = $this->resource->getTableName('catalog_product_entity_media_gallery_value');
$sql = <<<EOT
DELETE FROM {$gallery}
WHERE value_id IN (SELECT value_id FROM {$galleryValue} WHERE entity_id = {$product->getId()})
EOT;
$response = $this->resource->getConnection()->query($sql);
echo '(' . $product->getTypeId() . '): ' . $product->getSku() . " - No. Images: " . $response->rowCount() . "\n";
// // Or if you want to try the Magento way
//
// $images = $product->getMediaGalleryImages();
// foreach($images as $child){
// echo '(' . $product->getTypeId() . '): ' . $product->getSku() . ' - ' . $child->getFile() . "\n";
// $this->processor->removeImage($product, $child->getFile());
// }
//
// $this->productRepository->save($product);
} catch (\Exception $e) {
echo $e->getMessage() . "\n";
}
}