How to save special array data into Three MySQL table in PHP - php

I have JSON which need to insert into MySQL table.
What I already did is, convert it to array using:
$json_data = json_decode($geo_json, true);
and get an output of array but I do not know how to inset into second and third MySQL table.
My MySQL Table:
Table 1:
geo_id | user_id | geo_title | geo_description | geo_date |geo_status |geo_action |action_reason | geo_json | remote_ip | map_type |geo_snapshot
I can able to insert into above table easily but problem is in table two and Three listed below.
Table 2:
id | layer_id | map_id | layer_name | user_id | draw_type | latlng | radious
Table 3:
data_id | geo_key | geo_value | map_id | layer_id
Array I am getting:
Array
(
[type] => FeatureCollection
[features] => Array
(
[0] => Array
(
[type] => Feature
[properties] => Array
(
[action] => a
[poi_name] => a
[fac_type] => 17
[ph_number] => a
[hno] => a
[postcode] => a
[mail] => a
[str_nm] => a
[photo] => developer-page.png
[comment] => a
[url] => a
[sub_loc] => a
[employee] => a
)
[geometry] => Array
(
[type] => Point
[coordinates] => Array
(
[0] => 88.434448242188
[1] => 22.510971144638
)
)
)
[1] => Array
(
[type] => Feature
[properties] => Array
(
[action] => b
[poi_name] => b
[fac_type] => 18
[ph_number] => b
[hno] => b
[postcode] => b
[mail] => b
[str_nm] => b
[photo] => 1475131600_developer-page.png
[comment] => b
[url] => b
[sub_loc] => b
[employee] => b
)
[geometry] => Array
(
[type] => Point
[coordinates] => Array
(
[0] => 88.321151733398
[1] => 22.50906814933
)
)
)
)
)
Now problem is to insert above data into two separate tables:
Table 2: This is only require to insert draw_type | latlng from above php array.
Example: draw_ type: point and latlng : coordinates
Table 3:
This is require to insert geo_key | geo_value | map_id | layer_id from above PHP array.
Example:
geo_key : properties [action,poi_name,fac_type,ph_number,hno,postcode,mail,str_nm, photo, comment, url, sub_loc, employee]
geo_value : [properties values ]
map_id :[this will be table 1 insert id]
layer_id : [this can be blank]
Please guide me and show me how to start.

$json_data["features"][$array_index]["geometry"]["type"]
For table2:
foreach($json_data["features"] as $info){
$type = $info["geometry"]["type"];
$latlng_0 = $info["geometry"]["coordinates"][0];
$latlng_1 = $info["geometry"]["coordinates"][1];
// DO INSRET with $type, $latling_0, $latling_1
$sql = "INSERT INTO Table2 (draw_type, latlng0, latlng1) VALUES ('".$type."','".$latlng_0."','".$latlng_1."')";
....
}
For table3:
Is 'map_id' a auto increment key in table1?
You'll need to know map_id first by select * where (conditions)
after successful insert data to table1
And if 'layer_id' can accept blank (null) data, it'll be fine if you don't specific value in INSERT command. Just make sure your table have correct settings.

Related

want to insert multidimensional array value into php database with unique value

I have one multidimensional-array and i want to insert into my database, there is one issue if one entry in my database and same entry is on my multidimensional-array that value should not insert again in my database.
$activity[] = array('user_id'=> $_SESSION['user_id'], 'choosen_date' => $ch_date, 'distance' => $distance, 'pace' => $pace );
Array
(
[0] => Array
(
[user_id] => 1200
[choosen_date] => 2018-12-11
[distance] => 1.72
[pace] => 12.4812
)
[1] => Array
(
[user_id] => 1200
[choosen_date] => 2018-12-09
[distance] => 3.17
[pace] => 3.8736
)
[2] => Array
(
[user_id] => 1200
[choosen_date] => 2018-11-14
[distance] => 2.26
[pace] => 6.3504
)
[3] => Array
(
[user_id] => 1200
[choosen_date] => 2018-11-07
[distance] => 0.53
[pace] => 3.6576
)
)
And following is my database entry
----------------------------------------------------
| S.No | user Id | choose date | distance | Pace |
----------------------------------------------------
| 1 | 1200 | 2018-12-09 | 3.17 | 3.8736 |
----------------------------------------------------
| 2 | 1200 | 2018-12-11 | 2.17 | 5.67 |
----------------------------------------------------
so here, in database S.no 1 and array index 1 both are the same entry so I want to insert rest value into my database. So how can I insert?
I am assuming that you are using MySQL database, you can use INSERT IGNORE INTO
or INSERT ON DUPLICATE KEY UPDATE
If you want to do it through PHP then you can try this.
$i=0;
foreach($activity as $key=>$val)
{
$sn_check=mysqli_query($con,"SELECT id FROM table WHERE S.No='$i'");
if(mysqli_num_rows($sn_check)==0)
{
$user_id=$val[$i]['user_id']; //all other values can be catch like this.
$query_insert=mysqli_query($con,"INSERT QUERY");
}
$i++;
}

Want to get relational table value in specified way in mysql

I have 2 table like below.
Table A
id | val_a
1 | a1
2 | a2
3 | a3
Table B
id | id_a| val_b
1 | 2 | b1
2 | 2 | b2
3 | 3 | b3
What is the best way to get data like below :
[
[0] => stdClass Object
(
[id_a] => 1
[val_a] => 'a1'
)
[1] => stdClass Object
(
[id_a] => 2
[val_a] => 'a2'
[table_b] => Array
(
[0] => stdClass Object
(
[id_b] => 1
[val_b] => 'b1'
)
[1] => stdClass Object
(
[id_b] => 2
[val_b] => 'b2'
)
)
)
[2] => stdClass Object
(
[id_a] => 3
[val_a] => 'a3'
[table_b] => Array
(
[0] => stdClass Object
(
[id_b] => 3
[val_b] => 'b3'
)
)
)
]
I am using Laravel 5.2. And achive this by foreach loop. But I don't know what is the best way to do. Can I do this by laravel or Mysql ? Thanks Ahead.
You can achieve this using Eloquent Model and hasMany relationship
for the first table Table A
class table_a extends Model
{ //define your primary key
protected $primaryKey = 'id_a'; /*you can skip this if id is your primary key*/
public function get_b_values(){
return $this->hasMany(table_b::class, 'id_b', 'id_a');
//foreign_key then local_key
}
}
for the second table Table B
class table_b extends Model
{
protected $primaryKey = 'id_b';
/*you can skip this if id is your primary key*/
}
Then you can access the element (exp id=2) you want like this:
table_a::find(2)->get_b_values;
UPDATE
Try this in your controller:
$results=table_a::with('get_b_values')->get();
Yes you can do it using laravel, take data from table_a and store row in a variable and run another query in table_b where id_a = id (table_a's id column) and store them into your defined variable.

php (PDO) simple way to turn rows in lookup table into simple array

given a very simple table structure thus:
mysql> describe songpart;
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | MUL | NULL | auto_increment |
| partName | text | NO | | NULL | |
+----------+---------+------+-----+---------+----------------+
which results in an array like this in php (when queried)
Array ( [0] => Array ( [id] => 1 [0] => 1 [partName] => Lead Guitar [1] => Lead Guitar )
[1] => Array ( [id] => 2 [0] => 2 [partName] => Bass Guitar [1] => Bass Guitar )
[2] => Array ( [id] => 3 [0] => 3 [partName] => Drums [1] => Drums )
[3] => Array ( [id] => 4 [0] => 4 [partName] => Keyboard [1] => Keyboard ) )
Am I missing some simple trick to turn this into a simple array with id as the key like so:
Array ( [1] => Lead Guitar
[2] => Bass Guitar
[3] => Drums
[4] => Keyboard )
or is it possible to get PDO to deliver an array like this?
TiA
You can simply use the PDO::FETCH_KEY_PAIR is you have only 2 columns in your result.
You can also use the PDO::FETCH_GROUP and PDO::FETCH_ASSOC together if you have more. Example :
$result = $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
This will yield an array indexed with the first column containing at each index an array of the result for this key. You can fix this by using array_map('reset', $result) to get your goal.
Example :
$result = array_map('reset', $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
Try this:
$records = $pdo->query('SELECT id, partName FROM myTable');
$records->setFetchMode(PDO::FETCH_KEY_PAIR);
print_r($records->fetchAll());
For that you need to set only your desired fields in iteration.
$part_name = [];
$records = $pdo->query('SELECT * FROM your_table');
foreach ($records as $row) {
$part_name[$row['id']] = $row['partName'];
}

show job title inside category but same category dont repeat

The following code:
$services = $this->find('all', array(
'contain' => array('Category','Country'),
'joins' => array(
array('table' => 'services_to_categories',
'alias' => 'ServiceCategory',
'type' => 'INNER',
'conditions' => array(
'ServiceCategory.service_id = Service.id'
)
)
),
'group' => 'Service.id'
));
return $services;
gives me this output:
Array
(
[0] => Array
(
[Service] => Array
(
[id] => 6
[job_title] => director
)
[Category] => Array
(
[0] => Array
(
[id] => 1
[category] => Accounting & Financial
)
[1] => Array
(
[id] => 3
[category] => Awards & Incentives
)
[2] => Array
(
[id] => 7
[category] => Data Management
)
)
)
[1] => Array
(
[Service] => Array
(
[id] => 11
[job_title] => d
)
[Category] => Array
(
[0] => Array
(
[id] => 7
[category] => Data Management
)
[1] => Array
(
[id] => 10
[category] => Internet Services
)
)
)
[2] => Array
(
[Service] => Array
(
[id] => 12
[job_title] => e
)
[Category] => Array
(
[0] => Array
(
[id] => 4
[category] => Business Consulting
)
[1] => Array
(
[id] => 7
[category] => Data Management
)
)
)
)
I need the output to be like below:
Accounting & Financial
job_title: director
Awards & Incentives
job_title: director
Data Management
job_title: director
job_title: d
job_title: e
Internet Services
job_title: d
Business Consulting
job_title: e
How does one use this array variable $services like in the above output?
Basically, all I did was to loop through the array and make a new array with the category as the key and the job title as an array of values. Then I just looped through my new array and spit out the key and values.
<?php
$category_array = array();
// LOOP THROUGH THE MAIN ARRAY AND RESTRUCTURE IT
foreach ($start_array AS $array_element) {
foreach ($array_element['Category'] AS $category) {
$category_array[$category['category']][] = $array_element['Service']['job_title'];
}
}
// LOOP THROUGH OUR NEW ARRAY AND PRINT OUT THE KEY AND VALUES
foreach ($category_array AS $department => $job_title_array) {
print $department;
foreach ($job_title_array AS $job_title) {
print "\njob_title: ".$job_title;
}
print "\n\n";
}
Here is a working demo
You can't solve this problem with a query.
What you want is something like this:
+------------------------+----------+
| Accounting & Financial | director |
+------------------------+----------+
| Data Management | director |
| +----------+
| | d |
| +----------+
| | e |
+------------------------+----------+
Obviously SQL works with tables, not nested trees, so this cannot be done.
1) SQL will give you this (using GROUP BY Service.job_title):
+------------------------+----------+
| Accounting & Financial | director |
+------------------------+----------+
| Data Management | d |
+------------------------+----------+
| Data Management | e |
+------------------------+----------+
2) Or this (using GROUP BY Category.category):
+------------------------+----------+
| Accounting & Financial | director |
+------------------------+----------+
| Data Management | director |
+------------------------+----------+
3) or this (without using GROUP BY):
+------------------------+----------+
| Accounting & Financial | director |
+------------------------+----------+
| Data Management | director |
+------------------------+----------+
| Data Management | d |
+------------------------+----------+
| Data Management | e |
+------------------------+----------+
In case 1 you're losing data: Data Management | director is no longer in the result.
In case 2 you're also losing data: Data Management | d and Data Management | e are no longer in the result.
So you'll have to go with case 3. Then manually (in code) transform this result into the nested array you want.
PS: These are pseudo results. The actual results will depend on a variety of factors concerning your database.

Redbeanphp - Getting data from foreign key index

Sorry for the vague title, if anyone would like to edit it to reflect more about what I am posting, please do so. Here is the situation. I have 3 tables:
support:
id | contact_id | title | problem | etc
supportlogin:
id | contact_id | login | pass | etc
contact:
id | first_name | last_name | email | etc
I am loading the support bean just fine, and am accessing the contact info:
$support=R::load('support',1);
echo $support->contact->first_name;
I want to echo the supportlogin information similarly:
echo $support->contact->ownSupportlogin->login;
Is this possible, and am I doing it the right way? I have tried the following ways with no success:
echo $support->contact->supportlogin->login;
echo $support->contact->ownSupportlogin->login;
echo $support->contact->ownSupportlogin[0]->login;
EDIT: MORE INFO
I did print_r($support->contact) and was given the data:
RedBean_OODBBean Object
(
[null:RedBean_OODBBean:private] =>
[properties:RedBean_OODBBean:private] => Array
(
[id] => 109
[phone] => 1234580970
[first_name] => Tim
[last_name] => Withers
)
[__info:RedBean_OODBBean:private] => Array
(
[type] => contact
[sys.id] => id
[tainted] =>
)
[beanHelper:RedBean_OODBBean:private] => RedBean_BeanHelperFacade Object
(
)
[fetchType:RedBean_OODBBean:private] =>
)
And then I did print_r($support->contact->ownSupportlogin) and this showed up:
Array
(
[13] => RedBean_OODBBean Object
(
[null:RedBean_OODBBean:private] =>
[properties:RedBean_OODBBean:private] => Array
(
[id] => 13
[link] => fecd4ef67e8c789efa1792f9ee0efff4
[login] =>
[password] =>
[receiveemails] => 1
[contact_id] => 109
[role] => 1
)
[__info:RedBean_OODBBean:private] => Array
(
[type] => supportlogin
[sys.id] => id
[tainted] =>
)
[beanHelper:RedBean_OODBBean:private] => RedBean_BeanHelperFacade Object
(
)
[fetchType:RedBean_OODBBean:private] =>
)
)
I can access it using: echo $support->contact->ownSupportlogin[13]->login;, but doing it dynamically seems to be a problem....
Figured it out, and will leave it up in case anyone else has a similar problem:
This will only work if you have a 1:1 relationship. Redbean populates the ownSupportlogin as an array of all supportlogin rows related to the contact. If one table can have many child tables, then you will need to loop through that array and pull out the data you want. If it is a 1:1 relationship, then you can use PHP's reset() to access the data of the first element in the array:
echo reset($support->contact->ownSupporlogin)->login;

Categories