How to use auto increment field in insert for CI 3 - php

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.

Related

Update column of current row

I'm looping through contacts, pulling out specific data then want to update a particular column on the current row. How can I do that?
The line is at the very bottom, I just want to change it from a 0 to 1.
require('../mailin.php');
$mailin = new Mailin("https://api.sendinblue.com/v2.0","Your access key");
$customer_data = $wpdb->get_results("SELECT * FROM imp_customer_log WHERE updated_in_sib = '0'");
foreach( $customer_data as $customer ) {
$customer_id = $customer[0];
$customer_event = $customer[1];
$customer_data = $customer[2];
$customer_sib = $customer[3];
$user = get_user_by( 'id', $customer_id );
$user_email = $user->user_email;
$data = array(
"email" => $user_email,
"attributes" => array(
$customer_event => $customer_data,
),
);
var_dump($mailin->create_update_user($data));
// Change updated_in_sib to 1 for current row
}
i assume that this is a wordpress. you can use the update function in wpdb something look like this.
$wpdb->update('imp_customer_log', ['customer_sib' => 1], ['id' => $customer_id]);
you can check the it on documentation. https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows
for php (not wordpress)
$sql = "UPDATE imp_customer_log SET customer_sib=1 WHERE id=" . $customer_id;
$connection->query($sql);
I think you're using Wordpress. Take a look at these wordpress docs for update, used just like get_results() in your question.
https://developer.wordpress.org/reference/classes/wpdb/update/
$wpdb->update( string $table, array $data, array $where, array|string $format = null, array|string $where_format = null )

Insert unique record in MySQL

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

codeigniter auto increment foreignkey

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.

$this->db->insert_id() seems to be wiping away my previous insert_id variables value

Here is the code:
$the_question = $_POST['question'];
$the_answer = $_POST['answer'];
$dummy_num[] = $_POST['dummy_answer_1'];
$dummy_num[] = $_POST['dummy_answer_2'];
$dummy_num[] = $_POST['dummy_answer_3'];
//Get Hidden Test ID and Q_order
$test_id = $_POST['test_id'];
$q_order = $_POST['q_order'];
//Submit Question
$data_submit_q = array (
'type' => 1,
'question' => $the_question,
'done' => 1
);
$this->db->where('test_id', $test_id);
$this->db->where('q_order', $q_order);
$this->db->update('questions', $data_submit_q);
$question_id = $this->db->insert_id();
$time_created = date('Y-m-d H:i:s');
//Submit Answer
$data_submit_a = array (
'test_id' => $test_id,
'question_id' => $question_id,
'option' => $the_answer,
'company_id' => $data['company']->id,
'job_id' => $data['session_job_id'],
'time_created' => $time_created
);
$this->db->insert('options', $data_submit_a);
$answer_id = $this->db->insert_id();
//Let question know that answer is right.
$data_submit_qr = array (
'answer_id' => $answer_id
);
$this->db->where('id', $question_id);
$this->db->where('test_id', $test_id);
$this->db->update('questions', $data_submit_qr);
Setting the answer id removes the value of the question id, then on updating the database the answer id has no value also. Even though it does right before.
The method $this->db->insert_id() retrieves the ID when performing database inserts (as the name hints).
You're using it after an update, that's why your $question_id gives problems (I think it would be set to FALSE, but I don't know for sure what does that method return when called on the wrong context). WHen you do your last update you use this as a WHERE condition, and if it is not set...
It's not that your second call to insert_id() wipes out the first, I suspect is more like the first one is already NOT SET (or FALSE)
It seems that there is a bug with insert_id, you can try using:
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$lastInsertId = $row['LAST_INSERT_ID()'];
Hope it helps

am i writing this update query correctly?

this is the sql query i used before i switch to codeigniter
UPDATE transaction SET due_amount = to_pay-$payment_amount WHERE id = '$id'
with codeigniter
$this->db->set('due_amount', 'to_pay-'.$payment_amount, FALSE);
$this->db->where('id', $id);
$result = $this->db->update('transaction');
in the codeigniter code am i writing $this->db->set correctly?
Regards
You should do it like this:
$this->db->where('id', $id);
$result = $this->db->update('transaction',array('due_amount'=>'to_pay-'.$payment_amount));
Hope this helps.
There are multiple variants to use the updateDocs function. Yours doesn't look specifically bad (I would however don't bypass escaping if not for a specific reason), maybe you prefer to use an array (or object) to provide the data being updated:
$data = array(
'due_amount' => 'to_pay-'.$payment_amount,
);
$this->db->update('transaction', $data, sprintf('id = %d', $id));
I think here could be some issue with $this->db->set
Standard way of updating content in codeignitor is this
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
Produces:
UPDATE mytable
SET title = '{$title}', name = '{$name}', date = '{$date}'
WHERE id = $id

Categories