Codeigniter Error - Duplicate entry '2' for key 'PRIMARY' UPDATE `tickets` SET `id` = '2', `status` = 1 - codeigniter

I'm building a support system with Codeigniter 3.
When the ticket status is 0, there is no problem, but when I want to set the current status to 1, I get an error.
My database "TNYINT" Length 1 default value 0
if i send it as 0 it's ok but when admin posts this i have to make it 1.
/*** Reply Ticket Post */
public function admin_reply_ticket_post()
{
/// Admin Authority Checkup Getting Started
adminCheck();
// Admin Authority Check End
$data = array(
'ticket_id' => $this->input->post('ticket_id'),
'admin_id' => $this->session->userdata('adminid'),
'first_name' => $this->session->userdata('first_name'),
'last_name' => $this->session->userdata('last_name'),
'message' => $this->input->post('message')
);
$this->db->insert('tickets_sub', $data);
// Make Ticket Status "in the transaction"
$data = array(
'id' => $this->input->post('ticket_id'),
'status' => 1 ,
);
$this->db->update('tickets', $data);

Right now, you're giving all the records in the tickets table a new id and status, that's why you're getting the "Duplicate" error. You need to add a WHERE clause to specify which record to update:
// Make Ticket Status "in the transaction"
$data = array(
'status' => 1 ,
);
$this->db->where('id' => $this->input->post('ticket_id'));
$this->db->update('tickets', $data);
Or even shorter:
// Make Ticket Status "in the transaction"
$data = array(
'status' => 1 ,
);
$this->db->update('tickets', $data, array('id' => $this->input->post('ticket_id')));
See: https://www.codeigniter.com/userguide3/database/query_builder.html#updating-data

Related

How make a register form codeigniter with different database table

I tried to make a register form on a multiuser website with a different database table.
Eg when user1 registers, the data will be entered in table "user1",
when user2 registers, entered in table "user2".
I can only enter user1 and user2 into the same table.
This is my code using role_id
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
You can do this by applying condition on role_id but this is only possible if there are only a number of users. If there are many users and you want to make a separate table for each one of them, try Database Forge Class(Bad practice)
I've written a possible solution for your question, comments are mentioned wherever necessary. See if it helps you.
Controller
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
$this->xyz_model->xyz_function($data); // load xyz_model and call xyz_function with $data parameters
Xyz_model
function xyz_function($data){
$table = 'user1'; // default value
if($data['role_id'] != 1){ // other value is 2 -- assuming only 2 users are there(if not user if else or switch)
$table = 'user2';
}
$this->db->insert($table, $data);
return $this->db->insert_id();
}

POST, Response and assertJson in phpunit testing

I have following test function to check the update data is correct or not.
It has no problem in updating.
My question is how to check the given parameters are correct after updated.
for example
if response.id == 1 and response.name = 'Mr.Smith'
assertcode = OK
else
assertcode = NG
public function user_update_info(){
$this->post('login',['email' => config('my-app.test_user'),
'password' => config('my-app.test_pass')]);
$response = $this->post('/update_info',[
'id' => 1,
'name' => 'Mr.Smith',
'post_code' => '142-4756',
'prefectural_code' => '15',
'address' => 'Merchat St.',]);
$response->assertStatus(200);
}
Assume your update_info route update User model.
Try below after your code,
$user = User::find(1);
static::assertTrue($user->id == 1 && $user->name = 'Mr.Smith');
To check if the response returns a json data you expect, you can use assertJson() method of the response object like so:
$response->assertJson([
'id' => 1,
'name' => 'Mr.Smith'
]);

Update multiple Rows in Codeigniter

I have been looking around but I have not found an answer yet. Kindly help if you know the answer.
How do you update multiple rows in CI?
In my MySQL:
I have column names:
ID, Settings Name, Settings Value ( Settings Name is Unique )
I have the ff Data:
ID = 1, Settings Name = "Hello" , Settings Value = "True"
ID = 2, Settings Name = "World", Settings Value = "Good"
and more ...
I also have a form that gets the Settings Value but I am not sure how to update it on the DB. How to update the True for the Hello being the Settings Name and update the Good for the World.
I heard about insert_batch() but is there an update_batch()?
Are you using Active record?
Yes there is an update batch: $this->db->update_batch();
$data = array(
array(
'ID' => 1 ,
'Settings Name' => 'Hello' ,
'Settings Value' => 'True'
),
array(
'ID' => '2' ,
'Settings Name' => 'World' ,
'Settings Value' => 'Good'
)
);
$this->db->update_batch('mytable', $data, 'where_key');
From the documentation:
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
There is indeed an update_batch() method available in CodeIgniter already.
You can use it your example like so:
$data = array(
array(
'ID' => 1,
'Settings Name' => 'Hello',
'Settings Value' => 'True'
),
array(
'ID' => 2,
'Settings Name' => 'World',
'Settings Value' => 'Good'
)
);
$this->db->update_batch('tableName', $data, 'id');
So what you have is an array of arrays, the children basically hold the data for each row in the database. The first parameter for update_batch() is the name of the database table, the second is the $data variable and the third is the column you want to use in the WHEN clause.
Here is a simple php code for perform this operations.
<?php
function basic_update($uwi='') {
$this->load->database();
$data = array(
'ID' => 1,
'Settings Name' => 'Hello',
'Settings Value' => 'True'
);
$this->db->where('ID', '1');
$this->db->update('<table name>', $data);
$data1 = array(
'ID' => 2,
'Settings Name' => 'World',
'Settings Value' => 'Good'
);
$this->db->where('ID', '2');
$this->db->update('<table name>', $data1);
}
In $this->db->where('ID', '1'); ID is your table field and 1 is the value.
In array first parameter will contain the table name, the second parameter is an associative array of values

CakePHP data not saving and validation not working

When my model goes to validate my form
it always come as false,
it doesn't save in the database.
I dont understand why this isn't working, it was working until I unbind on a few of my functions.
Here is my invoice model, it's supposed to check if there is to/biller in relationships_users table (relationship model).
<?php
class Invoice extends AppModel{
var $name='Invoice';
public $belongsTo = array(
'Relationship' =>array(
'className' => 'Relationship',
'foreignKey' =>'relationship_id',
)
);
var $validate = array(
'to' => array(
'relationshipExists' => array(
'rule' => array(
'relationshipExists'),
'message' => 'sorry you dont have a relationship with that user.'
),
),
);
public function relationshipExists($check){
$relationshipExists=$this->Relationship->find('count', array(
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
)
);
if ($relationshipExists>0) {
return TRUE;
}
else
return FALSE;
}
Here is my function in the invoices table
public function addinvoice(){
$this->set('title_for_layout', 'Create Invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
if($this->request->is('post')){
($this->Invoice->set($this->request->data));
if($this->Invoice->validates(array('fieldList'=>array('to','Invoice.relationshipExists')))){
$this->Invoice->save($this->request->data);
$this->Session->setFlash('The invoice has been saved');
}}else {
$this->Session->setFlash('The invoice could not be saved. Please, try again.');
}
}
What it's supposed to do is to check that to/biller are in the relationships_users table and then save the invoice to the invoice table, otherwise throw a message.
The conditions array seems strange to me:
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
That would search for Relationships with both partyone and partytwo set to to. You probably want to check if either of them is set to to:
'conditions' => array(
'OR' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
)
// get the value from the passed var
)

cookie not being set straight away

I have a basket cookie, before adding a product to the basket the function checks to see if a cookie exists or if a new cookie is required. This works fine when adding one item at a time but there are occasions when more than one item is added at the same time. Again if an old basket cookie exists this works fine. The problem is when no basket cookie exists and the function had to create one.
The first time it goes through, the cookie is created a database record is added ect.
The second time round the function we check for the cookie no cookie is found and another cookie is created etc.
$this->db->select('basket_id');
$this->db->from($this->basket_table);
$this->db->where('basket_id', get_cookie('basket_id'));
$check_basket = $this->db->get();
if($check_basket->num_rows > 0){
$basket_exists = 1;
}else{
$basket_exists = 0;
}
if($basket_exists == 0){
delete_cookie('basket_id');
$basket = array(
'lang_id' => $lang_id,
'currency_id' => $currency_id,
'customer_id' => $customer_id,
);
$this->db->insert($this->basket_table, $basket);
$basket_id = $this->db->insert_id();;
$cookie = array(
'name' => 'basket_id',
'value' => $basket_id,
'expire' => 60*60*24*30,
'domain' => 'REMOVED'
'path' => '/',
'prefix' => '',
);
set_cookie($cookie);
}else{
$basket_id = get_cookie('basket_id');
}
In order to set the cookie, you need to send it to the browser, - but this never happens if your function loops multiple times before you create a view.
So set the cookie prior to them using the basket, OR only check if the cookie needs to be set once, like this:
$this->db->select('basket_id');
$this->db->from($this->basket_table);
$this->db->where('basket_id', get_cookie('basket_id'));
$check_basket = $this->db->get();
if($check_basket->num_rows > 0) {
$basket = array(
'lang_id' => $lang_id,
'currency_id' => $currency_id,
'customer_id' => $customer_id,
);
$this->db->insert($this->basket_table, $basket);
$basket_id = $this->db->insert_id();
$cookie = array(
'name' => 'basket_id',
'value' => $basket_id,
'expire' => 60*60*24*30,
'domain' => 'REMOVED'
'path' => '/',
'prefix' => '',
);
set_cookie($cookie);
}
// Now run your basket logic here - knowing the cookie is setup
}

Resources