Insert data to different table in codeigniter - php

So I have 2 tables.
Table 1: (person_identity)
Id_person(PK), name, address, telp
Table 2: (Student)
Id_person(FK), no_student (PK), status, parent
How to input data to name, address, no_student, parent and status at the same time with the same Id_person but at 2 different table?

You can do like this
$dataPersonIdentity = ['name' => 'Abc', 'address' => 'This is address', 'telp' => 'this is telp'];
$this->db->insert('person_identity',$dataPersonIdentity);
$personIdentityId = $this->db->insert_id();
$dataStudent = ['Id_person' => $personIdentityId, 'no_student' => 8, 'status' => 1, 'parent' => 1];

do insert in the first table (person_identity)
and then do insert in the second table (student)

Related

Laravel save timestamp field to database

I have timestamp field
$table->timestamp('age')->nullable()->default(null);
I need save is field is value to database.
$dateOfBirth = Carbon::now()->subYears(intval($row['age']));
return Customer::updateOrCreate(['id' => $row['id']],['id' => $row['id'],
'name' => $row['name'],
'age' =>$dateOfBirth->getTimestamp(),
'email' => $row['email']]);
But got error
Incorrect datetime value: '871238720' for column 'age' at row 1 (SQL: insert into customers (id, name, age, email, updated_at, created_at) values (1, Annika Kane, 871238720, malattia#hotmail.com, 2022-08-10 18:45:20, 2022-08-10 18:45:20))
How fix it?

Insert records to either two tables or one table depending on if a record exists or not using Laravel query builder

I'm trying to insert records to either two tables or one table depending on if a record exists or not.
First table Authors
ID | Name
1 | Joe
2 | Sam
Second table Books
ID | author_ID | Book
1 | 2 | Book1
2 | 2 | BookYYY
3 | 1 | BookABC
What I want to accomplish is to check if author exists first, if not insert author and his book and if it DOES exists insert just the book with the right author ID
Here is what I've attempted so far that doesn't seem to work.
$result = DB::table('authors')
->where('name', $data['author_name'])
->where('username', $data['author_username'])->pluck('id');
if(is_null($result)){
//Not in table add new author
$id = DB::table('authors')->insertGetId(
['name' => $data['author_name'], 'username' => $data['author_username']]
);
//Add book
DB::table('books')->insert(
['author_id' => '.$id.', 'name' => "Book777"]
);
}
else{
//Is in table insert just book
DB::table('books')->insert(
['author_id' => '.$result.', 'name' => "Book777"]
);
}
So I'm trying to add author with Book name "Book777" but if author does exists in DB get the author ID and insert just the book.
Thank you all for helping me with this! Appreciate any help.
Consider using ORM. With Eloquent you can change all your code to just this:
$author = Author::firstOrCreate(['name' => $data['author_name'], 'username' => $data['author_username']]);
$author->books()->create(['name' => 'Book777']);
With Query Builder you can do this:
$attributes = [
'name' => $data['author_name'],
'username' => $data['author_username']
];
$author = DB::table('authors')->where($attributes)->first();
$authorId = is_null($author) ? DB::table('authors')->insertGetId($attributes) : $author->id;
DB::table('books')->insert(['author_id' => $authorId, 'name' => "Book777"]);
I'm not sure if it's work or not but hope this helps
$result = DB::table('authors')
->where('name', $data['author_name'])
->where('username', $data['author_username'])->pluck('id');
if(!empty($result)){
//Is in table insert just book
DB::table('books')->insert(
['author_id' => $result, 'name' => "Book777"]
);
}
else{
//Not in table add new author
$id = DB::table('authors')->insertGetId(
['name' => $data['author_name'], 'username' => $data['author_username']]
);
//Add book
DB::table('books')->insert(
['author_id' => $id, 'name' => "Book777"]
);
}

fetch values in listbox from two table using joins

User Table -
column name - location_id
values = 4,5
Location table
column name - id , location_name
values = 4 nagpur
5, Akola
i want to display location names in listbox by joining location_id of user table,
Suppose in location_id column of user table 4,5 values are present then in my select box this only displays nagpur, Akola from location table.
i cannot understand how to explode values of location_id table before select and display only those values which are available in location_id column from location table.
public function getUserLocations() {
$this->loadModel('User');
$getlocations = $this->User->find('list', array(
'fields' => array('Location.id','Location.location_name'),
'joins' => array(
array(
'table' => 'locations',
'alias' => 'Location',
'type' => 'LEFT',
'conditions' => array('FIND_IN_SET(User.location_id,Location.id)')
)
),
));
$this->set('getlocations', $getlocations);
}
below is my code ..
Explode the variable like this :
$getlocations = $this->User->find('list', array(
'fields' => array('Location.id'));
$location_ids[] = explode (',', $getlocations);
Now you will get the data in array format. Modify it according to your needs

GroceryCRUD : How to set field dropdown

I just code with GroceryCRUD,
This is my Database:
a_guest_data
guest_no
register_date
name
gender
birthday
address
city
country
phone
email
ref
status
date_modified
a_table_data
id_table
tbl_name
group_name
status
seat
party_date
locked
pos_tbl
date_modified
a_table_group
id_table
guest_no
priority
This is my Code for the Controller:
public function guest_management()
{
$crud = new grocery_CRUD();
$crud->set_table('a_guest_data');
$crud->set_subject('Guest');
$crud->set_relation_n_n('tables', 'a_table_group', 'a_table_data', 'guest_no', 'id_table', 'tbl_name');
$crud->unset_columns('register_date','layout_no', 'date_modified', 'ref');
$crud->fields('name', 'register_date', 'gender', 'birthday', 'tables', 'address', 'city', 'country', 'phone', 'email', 'ref', 'status' );
$crud->field_type('country','dropdown', array('Indonesia' => 'Indonesia', 'Others' => 'Others'));
$crud->field_type('gender','dropdown', array('Male' => 'Male', 'Female' => 'Female'));
$crud->field_type('status','dropdown', array('1' => '1', '2' => '2'));
$output = $crud->render();
$this->_example_output($output);
}
And I have the form like this
In the field Tables, I want to set the dropdown fields that only can choose 1 table (The Fact is, now in the field Tables, I can choose many options table. *See in the picture, I choose Table 1, 45, 6, 34).
How can I do that?
This behavior is due to your database structure. If you only want one table value you need your database structure to be "1-n database relation"
Documentation for about database relationships
What you want to achieve in grocery crud terms is set_relation.
Syntax for set_relation:
void set_relation( string $field_name , string $related_table, string $related_title_field [, mixed $where [, string $order_by ] ] )
Docs for set_relation
In the end your priority field will also be in the table a_guest_data
You are using a multiple select input, try removing MULTIPLE markup.
It depends on what type of select you are using.

Best match using MySQL and PHP

I'm tackling my first project using PHP/MySQL in which I have a list of cities and ratings from 1-5 in certain categories (Food, Shopping, etc.). What I'm wanting to do is evaluate each row (each City), when a form is submitted on whether the categories are important or not.
This is how I want it to work.
Say, for example:
1. Chicago Food: 4, Shopping: 4, Nightlife: 4
2. New York Food: 4, Shopping: 5, Nightlife: 5
3. Boston Food: 5, Shopping: 4, Nightlife: 3
(the ratings are just for example)
And the user says that Food isn't important. Therefore the code will only evaluate Shopping and Nightlife... New York ends with 10, Chicago with 8 and Boston with 7.
As I have a list of around 35-40 cities that I want to evaluate on each category (if the user deems it "important") dynamically, and the winner will be the highest number at the end of the evaluation.
Does anyone have any ideas on how to go about this? I have the table built in MySQL with all the ratings, just need to write the code out now.
What I've tried: bringing in all of the values using arrays, but I've found it difficult to loop through each of the rows... help!
You can accomplish this task with just a little bit of PHP code and an appropiate SQL statement.
Here is a possible solution:
$important_cat = $_POST['categories']; //which is an array
$sql = "SELECT city, sum(".implode(' + ',$important_cat).") AS cat
FROM tbl
ORDER BY cat DESC";
//query sql
Assuming database tables similar to this (at least, they should be normalized in this fashion):
city ( id, name );
category ( id, name );
rating ( city_id, category_id, rating );
... with an array of interests similar to this:
$interests = array(
'Food',
'Shopping'
);
... the following sql:
$sql = 'SELECT
city.name as city,
GROUP_CONCAT( category.name || ": " || rating.rating, ", " ) as ratings,
SUM( rating.rating ) as totalRating
FROM
rating
JOIN
city
ON city.id = rating.city_id
JOIN
category
ON category.id = rating.category_id
WHERE
category.name IN( ' . implode( ',', array_map( array( $db, 'quote' ), $interests ) ) . ' )
GROUP BY
city.name
ORDER BY
totalRating DESC';
(I assumed the use of PDO, utilizing PDO::quote() for escaping here, but substitute the callback array( $db, 'quote' ) with whatever quoting/escape mechanism your mysql library offers)
... will yield a result set similar to this (I've populated random rating data for my example):
array (
0 => array (
'name' => 'Chicago',
'ratings' => 'Food: 3, Shopping: 3',
'totalRating' => '6'
),
1 => array (
'name' => 'New York',
'ratings' => 'Food: 1, Shopping: 4',
'totalRating' => '5'
),
2 => array (
'name' => 'Seattle',
'ratings' => 'Food: 4, Shopping: 1',
'totalRating' => '5'
),
3 => array (
'name' => 'Los Angeles',
'ratings' => 'Food: 2, Shopping: 2',
'totalRating' => '4'
),
4 => array (
'name' => 'Boston',
'ratings' => 'Food: 1, Shopping: 2',
'totalRating' => '3'
),
5 => array (
'name' => 'San Francisco',
'ratings' => 'Food: 1, Shopping: 1',
'totalRating' => '2'
)
)
If you only need the first result, append LIMIT 1 to the sql query.
This should give you an idea of how to go about accomplishing what you want.
Above all: let MySQL do all the work (filtering, sorting) — not PHP.

Categories