How to check if a column exists in query builder Codeigniter 3?
my database table name is "tags" and this table have two column (post_id and tag) here is my code to add tags to post:
//add post tags
public function add_post_tags($post_id)
{
//tags
$tags = trim($this->input->post('tags', true));
$tags_array = explode(",", $tags);
if (!empty($tags_array)) {
foreach ($tags_array as $tag) {
$tag = trim($tag);
if (strlen($tag) > 1) {
$data = array(
'post_id' => $post_id,
'tag' => trim($tag),
'tag_slug' => str_slug(trim($tag))
);
if (empty($data["tag_slug"]) || $data["tag_slug"] == "-") {
$data["tag_slug"] = "tag-" . uniqid();
}
//insert tag
$this->db->insert('tags', $data);
}
}
}
}
I want to check if data exists in the database update the post_id column if not exist insert new data
"post_id" column like "5,8,9"
I want to add the post number to the previous numbers when I update "post_id" column
for example after update "post_id" column This table is like this "5,8,9,11" here 11 is my last post id
Try using replace() instead :
$this->db->replace('tags', $data);
Basically it inserts a new record if it doesn't exist, it updates it according to its primary or unique key if it does exist.
Related
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);
}
}
I am using the below code for insert data into DB.
if (isset($_POST['file_edit_note']) && isset($_POST['file_notes']) && !empty($_POST['file_edit_note'])) {
$my_post = array();
$my_post['ID'] = $_POST['file_edit_note'];
$my_post['post_content'] = $_POST['file_notes'];
$wpdb->insert($wpdb->prefix.'posts', array(
"post_content" => $_POST['file_notes'],
"post_parent" => $_POST['file_edit_note']),array( '%s'), array('%d'));
wp_redirect(get_permalink() . '?upd=1');
}
And,here the post ID is the parent. I try to get the post id and insert into the post_parent column on the child row. This part is working.
now i tried to retrieve the data in a loop.because when I open the parent in front end all the child comes from the parent.
<?php echo !empty($file->post_content)?$file->post_content:'Content not found.'; ?>
I am new to PHP. Please give me any Suggestions.
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
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 am adding data to three tables, I needed to get the last ID of the first table to use in the second table, which was successful with $this->db->insert_id() function, Trying that with the second table still gives me the ID of the first table. The arrangement of my code is:
function addcrm() {
//Post data collection array from the webform form
$customerdata = array(
"salutation"=>$this->input->post('salutation'),
"mobilenumber"=>$this->input->post('mobilenumber'),
"emailaddress"=>$this->input->post('emailaddress')
);
$this->db->insert('api_customer', $customerdata);
$customer=$this->db->insert_id();
$leaddata = array(
"fieldrep"=>$this->input->post('fieldrep'),
"fk_customerID"=>$customer,
"te"=>$this->input->post('takage'),
"othercost"=>$this->input->post('othercost')
);
$this->db->insert('api_lead', $leaddata);
$leadID = $this->db->insert_id();
for ($i =0; $i<count($_POST['w_product']); $i++){
$productdata = array(
"name" => $_POST['w_product'][$i],
"type" => $_POST['w_type'][$i],
"cost" => $_POST['w_cost'][$i],
"fk_leadID"=> $leadID
);
$this->db->insert('api_prod',$productdata);
}
$url = base_url('cXXXXXXXXXXXXXX);
redirect($url);
}
You are missing something obviously in the second call. ;)
$customer = $this->db->insert_id();
$leadIdD = $this->db->insert_id;
See? :)
Try working with the following methods:
$this->db->start_cache(); // Before query
$this->db->stop_cache(); // After query
$this->db->flush_cache(); // Clear query
This way you make clear and flushed queries.
if you are using an auto increment table you may try using MYSQL_LAST_INSERT_ID();
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html