In my application i have function to insert data to mysqldb and have more one image for one news and in database I make news id as foreign key in upload table and all inserts is work fine but the problem news FK in upload table when i insert data the first row inserted take the value i set it and the other take auto increment so the next you found code :
the inserted data in upload table
as you se the correct data is row have id 31 and the other is auto increment
the code I insert by him ;
the controller
public function insertNews() {
$this->do_one_upload();
$this->load->model('newsModel');
$this->load->model('fileModel');
$ad_ne_data = array(
'titel' => $this->input->post('ad_news_title') ,
'content' => $this->input->post('ad_news_content') ,
'news_category_id' => $this->input->post('ad_news_category') ,
'img_url' => $this->do_one_upload()[1]['full_path'],
'created_at' => date("Y-m-d")
);
$this->newsModel->addNews($ad_ne_data);
$i=0;
while($i < count($this->do_one_upload())) {
// var_dump($this->do_one_upload());
$ad_imgs_news =array(
'title' => $this->do_one_upload()[$i]['client_name'],
'file_path' => $this->do_one_upload()[$i]['full_path'],
'type' => $this->do_one_upload()[$i]['file_type'],
'size' => $this->do_one_upload()[$i]['file_size'],
'img_news_id' => $this->newsModel->getLastNewsId()
);
$i++;
$this->fileModel->addUpload($ad_imgs_news);
var_dump($ad_imgs_news);
}
}
the news model
the get Last news id inserted ;
public function getLastNewsId()
{
$last_id = $this->db->insert_id();
return $last_id;
}
the upload inset method in upload model
public function addUpload($data)
{
// $this->db->set('name', $name);
$this->db->insert('upload', $data);
}
So where the problem are in db or in code or???
Thanks, Regards
try to return
$last_id = $this->db->insert_id();
from
$this->newsModel->addNews($ad_ne_data);
Get the insert_id immediately after the query in addNews function.
Related
i'm using maatwebsite laravel excel to import some data from excel to database. But i want to add some custom ID with incremental value for each row of data.
For now, i'm able to import data with some input value form together.
DataImport file
class DataImport implements ToModel, WithStartRow{
public function model(array $row)
{
return new Tempdat([
'employee_id' => ??? (combination of client_code +1)
'name' => $row[1],
'gender' => $row[2],
'bod' => $this->transformDate($row[3]),
'engagement_code' => request('engagement_code'), //from input form
'client_code' => request('client_code'), //from input form
]);
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
public function startRow(): int
{
return 2;
} }
DataController file
public function ImportExcel(Request $request)
{
$this->validate($request,[
'file' => 'required|mimes:xls,xlsx',
'engagement_code' => 'required',
]);
$file = $request->file('file');
$clientCode = request('client_code');
$engagementCode = request('engagement_code');
$todayDate = date('dFY');
$file_name = $engagementCode.'_'.$todayDate.$file->getClientOriginalName();
$file->move('tempdat',$file_name);
Excel::import(new DataImport, public_path('/tempdat/'.$file_name));
return redirect()->route('dashboard.tempdat.index');
}
What i'd like to do is to add "employee code" which is combination of "client_code" + 1 for every row. for example if client_code is ABCD and there is 3 rows of data imported then the employee_code will be :
ABCD0001
ABCD0002
ABCD0003
...
i'm already searching for count rows but nothing found yet.
Counting rows will bring you problems whenever you remove a single record from the table: You won't be able to insert new rows if your primary employee_id field has UNIQUE key, or you will start inserting duplicated IDs.
Generating the ID in PHP isn't my recomendation either since you could face integrity problems if two records are trying to be stored simultaneously.
I would use the default model's model_id field with autoincrement to make sure that I won't have problems with id assignation, and inmediatly after saving the record I would update the id for the employee_id field which can be also keyed as "primary" in order to be indexed and accessed efficiently.
For example:
class MyModel extends Model {
public function save() {
if(parent::save()) {
$this->update['employee_id' => "ABCD".$this->id];
}
}
}
I haven't still realized how the Excel library you're using handles the model, but I supposed it can be specified somewhere along the process.
I am able to generate incremental id in laravel excel using this:
https://github.com/haruncpi/laravel-id-generator
$config = [
'table' => 'table_name',
'length' => 7,
'field' => 'employee_id',
'prefix' => request('client_code'),
'reset_on_prefix_change' => true,
];
$employee_id = IdGenerator::generate($config);
so, everytime import executed, employee_id will generated on its own following with client_code prefix (ex: ABCD001, ... )
I have a Codeigniter application which I used tags. I have a code that adding new tags and inserted it to the database and by inserting, I want to get the insert_id of the tag to be inserted to a relational table. I have no problem regarding with the table structure. Here is my table structure:
Tags table:
My problem is with this code which is I don't know why it returns an insert_id of zero but when I look at in the database, it was inserted from the tags table correctly.
Here is my code:
if (count($user_tags) > 0) {
foreach ($user_tags as $user_tag) {
$this->query->insert('tags', array('tag' => $user_tag));
$new_tag_id = $this->db->insert_id();
print_r($new_tag_id);
// $data = array(
// 'user_id' => $new_user_id,
// 'tag_id' => $new_tag_id
// );
// $this->query->insert('user_tags', $data);
}
}
Try
$this->db->insert
instead of
$this->query->insert
if (count($user_tags) > 0) {
foreach ($user_tags as $user_tag) {
$this->db->insert('tags', array('tag' => $user_tag));
$new_tag_id = $this->db->insert_id();
print_r($new_tag_id);
}
}
SELECT NEXT VALUE FOR contract_seq
//it will return next value of sequence 1, 2, 3 etc..i need to insert this sequence number to the database table.Using codeigniter i want to insert sequence number to database table
INSERT dbtest.contract (Contract_no) VALUES (NEXT VALUE FOR pestcontrol.contract_seq) // error Invalid object name 'pestcontrol.contract_seq'.
I think you haven't returned inserted id in model.Try this :
public function save_contract($data){
$insert_id = 0;
if($this->db->insert("contract", $data)){
$insert_id = $this->db->insert_id();
}
return $insert_id;
}
CONTROLLER
public function contract_submitted() {
$data = array(
'line_of_business_id' => $this->input->post('busi'),
'Contact_name' => $this->input->post('name')
);
$lastID= $this->modal_create_contract->save_contract($data);
if(!$lastID){
//Show Error
}
$data['last_id']=$lastID;
$this->load->view('contract',$data);
}
I am inserting data to payments table where Ref column needs to be unique. In below code, with $ref=$_POST['PAYMENT_ID']; I am inserting always a new ref no with other column value in each post back. Sometimes it is posting duplicate ref no. I am trying to keep the ref no unique.
For this I have written following code.What I am trying to do is if existing Ref Column value doesn't match with new $ref=$_POST['PAYMENT_ID'] value then it will insert data.But it is not working and inserting ref no yet it is matched with new ref no.
How can I do this?
<?php
$ref=$_POST['PAYMENT_ID'];
$pending = "Pending";
$method = "Uploaded funds";
$today = date('Y-m-d');
$time=$_POST['TIMESTAMPGMT'];
$type = "Pm";
$table_payments = $wpdb->prefix . "payments";
$check=$wpdb->get_results("SELECT Ref FROM $table_payments");
$checkrows=mysqli_num_rows($check);
if ($checkrows!=$ref) {
if($hash2==$_POST['V2_HASH']){
$wpdb->insert( $table_payments, array(
'Method' => $method,
'Today' => $today,
'Time' => $time,
'Ref' => $ref,
'Batch' => $batch,
'Type' => $type,
'Status' => $pending,
'User' => $me
));}}
?>
The problem is, $Ref is a user's submitted value and $checkrows holds the total number of rows in $table_payments table. And that's why the condition if ($checkrows!=$ref) { ... is failing.
You have to change your SQL query and the subsequent code in the following way,
// your code
$table_payments = $wpdb->prefix . "payments";
$check=$wpdb->get_results("SELECT * FROM $table_payments WHERE Ref = '$ref'");
$checkrows=$wpdb->num_rows;
if ($checkrows == 0) {
// do INSERT operation
}
Moreover, you should make Ref column of your table unique
I try to insert data to a table in CI 3 that has fields as below:
pageid is auto increment and I write code in model as this:
$data = array(
'title'=>$title,
'description'=>$des,
'url'=>'page/view/'.pageid
);
$this->db->insert('page',$data);
The problem is that the pageid is unknown as the field name. What should I do because I want to concatenate pageid to url?
You need two query for it
1)You need to insert title and description first and get last page id from database
$data = array(
'title' => $title,
'description' => $des
);
$this->db->insert('page', $data);
$page_id = $this->db->insert_id();// get last pageid
2)Update url second
$data = array(
'url' => 'page/view/'.$page_id
);
$this->db->where('pageid'$page_id);// update with page id
$this->db->update('page', $data);
OK so you can add all data first then after insert just update the url
field.
$data = array(
'title' => $title,
'description' => $des,
'url'=>'page/view/'
);
$this->db->insert('page', $data);
$page_id = $this->db->insert_id();
2)Now update URL
$update= array(
'url' => 'page/view/'.$page_id
);
$this->db->where('page_id'$page_id);
$this->db->update('page', $update);
Hope this will help you
Common & Easy Method
Goto
Phpmyadmin
select your database, then go to page table.
Click structure on top.
Click Change, in front of id field.
Then there is check box with AI(Auto Increment)
Check that and click save
If with code(use this)
public function FunctionName()
{
$query = $this->db->query("SELECT id FROM pages ORDER BY id DESC LIMIT 1");
$result = $query->result_array();
$id = $result['id']; // or some times $result[0]['id']
$data = array(
'title' => $title,
'description' => $des,
'url' => 'page/view/'.pageid,
'id' => $id
);
$this->db->insert('page',$data);
}
Just do like this:
$data = array(
'title'=>$title,
'description'=>$des
);
$this->db->insert('page',$data);
$page_id = $this->db->insert_id();
//To pass page_id to url column
$this->db->where('page_id', $page_id);
$data_1 = array('url'=>'page/view/'.$pageid);
$this->db->update('page', $data_1);
You can first get the highest Auto-Incremented id from select query and then, Use insert query for inserting the new row.
eg.
$id = $this->db->query("Select max(page_id) AS page_id from pages");
if($id->num_rows() > 0){
$result = $id->result_array();
$page_id = $result[0]['page_id'] +1;
}
// if table is empty
else{
$page_id = 1;
}
$data = array(
'title' => $title,
'description' => $des,
'url'=>'page/view/'.$page_id );
$this->db->insert('page',$data);
Please check it image for add auto increment id in phpmyadmin.