A Select Statement that would do the following - php

I am just learning how to wrap my head around sql and php. I have 4 tables structured as follows
+-----------+ +------------+ +---------+ +----------+
| Project | | Slide | | Shape | | Points |
+-----------+ +------------+ +---------+ +----------+
| id | | id | | id | | id |
+-----------+ | project_id | | cont_id | | shape_id |
+------------+ +---------+ | x |
| y |
+----------+
As you can see the tables are linked by id all the way down to points meaning a project will contain a number of slides that contain a number of shapes that contain a number of points.
I have a SQL query
SELECT slide.`id`, shape.`id`, points.`x_point`, points.`y_point`
FROM `project`, `slide`, `shape`, `points`
WHERE 1 = slide.`project_id`
AND slide.`id` = shape.`slide_id`
AND shape.`id` = points.`shape_id`
What I want is to take the results of this query that look like this
[0] => stdClass Object
(
[id] => 27
[x] => 177
[y] => 177
)
[1] => stdClass Object
(
[id] => 27
[x] => 178
[y] => 423
)
[2] => stdClass Object
(
[id] => 27
[x] => 178
[y] => 419
)
[3] => stdClass Object
(
[id] => 27
[x] => 178
[y] => 413
)
[4] => stdClass Object
(
[id] => 27
[x] => 181
[y] => 399
)
[5] => stdClass Object
(
[id] => 27
[x] => 195
[y] => 387
)
[6] => stdClass Object
(
[id] => 27
[x] => 210
[y] => 381
)
[7] => stdClass Object
(
[id] => 27
[x] => 231
[y] => 372
)
[8] => stdClass Object
(
[id] => 27
[x] => 255
[y] => 368
)
[9] => stdClass Object
(
[id] => 27
[x] => 283
[y] => 368
)
... AND CONTINUED FOR A LONG TIME
What I want is to convert this beastly array of crap into something that more resembles this
[9] => stdClass Object
(
[id] => ID OF LIKE SHAPES
[x] => Array(ALL THE X POINTS)
[y] => ARRAY(ALL THE Y Points)
)
I cannot for the life of me figure out how to convert this to such an array.
If it cannot be done with the query I designed is there a better query. Maybe one that grabs the points then takes that puts it into an array that of the points... I think I just got an Idea...
New Info,
So I added an answer to this question, I don't know if that's the standard way. To help out other answers if mine is not a good solution I will add my thought process here as well.
Check out my answer bellow for more info.
Also how does an ORM compare to my algorithm bellow?

Using an ORM like Doctrine, you would simply model it like
/**
* #Entity
*/
class Project
{
/**
* #Id #GeneratedValue
* #Column(type="integer")
*/
private $id;
/**
* #OneToMany(targetEntity="Slide", mappedBy="project")
*/
private $slides;
public function __construct()
{
$this->slides = new \Doctrine\Common\Collections\ArrayCollection;
}
}
/**
* #Entity
*/
class Slide
{
/**
* #Id #GeneratedValue
* #Column(type="integer")
*/
private $id;
/**
* #ManyToOne(targetEntity="Project", inversedBy="slides")
* #JoinColumn(name="project_id", referencedColumnName="id")
*/
private $project;
/**
* #OneToMany(targetEntity="Shape", mappedBy="slide")
*/
private $shapes;
}
And so on...
See http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html#one-to-many-bidirectional
Of course, there's a fair amount of setup and processing overhead involved but you'll appreciate an ORM as your domain model becomes more complex.

So I have been working on this a while and I came up with my own answer. I would love input because I think it is probably the BAD way to do this.
Here is my thought process. One Query is great but what if we build the results array incrementally. What I mean is we can build the results array by traversing through the tables with designed SELECT statements.
Here is the code I comment it because I am having a hard time describing my algorithm in just words.
/* $cur_project is set above from an input value. Assume any int
The algoritim Traverses a series of results and puts them into the proper places in a usable array.
The algorithim has an query count of NumberOfSlides + 2(NumberOfSlides)+1 which seems really high
For real word application if querying the DB is as bad as everyone says.
*/
// A blank array to build up
$projectArray = Array();
// I just want to see how many queries this thing generates
$queryCount = 0;
// Query 1 - This query will get all slides in a project.
$slide_id = $this->db->query('SELECT slide.`id`
FROM `slide`
WHERE slide.`project_id` = '.$cur_project);
$queryCount++;
//Now traverse the results to Query 1
foreach ($slide_id->result() as $slide_id){
// In the project array add an element with the key that is
// the slide_id for all slides in that project. Then for each
// key also create a new empty array at each added element
$projectArray[$slide_id->id] = Array();
// Query 2 - grab all the shapes that match the current slide in the current project!
// This is where things get inefficient.
$shape_id = $this->db->query('SELECT shape.`id`
FROM `shape`
WHERE shape.`slide_id` = '.$slide_id->id
);
$queryCount++;
// Traverse the results to Query 2
foreach ($shape_id->result() as $shape_id) {
// For every slide now create a key that matches the shape and fill that array with
// info I need such as an array of the points.
$projectArray[$slide_id->id][$shape_id->id] = Array(
'x_points' => Array(),
'y_points' => Array()
);
// Query 3 - Ask the DB for x/y points for the current shape. You can see how for slides with lots of shapes
$points = $this->db->query('SELECT points.`x_point`, points.`y_point`
FROM `points`
WHERE points.`shape_id` = '.$shape_id->id
);
$queryCount++;
// Traverse the Query 3 results
foreach ($points->result() as $point) {
// Populate the final arrays with the points
$projectArray[$slide_id->id][$shape_id->id]['x_points'][] = $point->x_point;
$projectArray[$slide_id->id][$shape_id->id]['y_points'][] = $point->y_point;
}
}
}
The above returns an array that looks like so
Array
(
[1] => Array
(
[27] => Array
(
[x_points] => Array
(
[0] => 177
[1] => 178
[2] => 178
[3] => 178
[4] => 181
...
Which can be interpreted as
Array
(
[SLIDE_ID] => Array
(
[SHAPE_ID] => Array
(
[x_points] => Array
(
[0] => 177
[1] => 178
[2] => 178
[3] => 178
[4] => 181
...
My problem with this solution is what I say in my top comment. I think you could duplicate these results with an array search for the original results as listed in the answer. That seems worse though.
Please for the life of me tell me how to improve this any comments on it will help me.
Thanks a lot.

I hope this help:
<?php
$newStdClass['id'] = $stdClass[$i]['id'];
for($i=0;$i<count($stdClass);$i++)
{
$newStdClass['x'][] = $stdClass[$i]['x'];
$newStdClass['y'][] = $stdClass[$i]['y'];
}
?>
Assuming $sttClass is your array of crap as you said :D.

Related

How do I get MySQL query result as nested array using PHP?

Let's say I have this simple table where pos_level is the level of the position and pos_under is that the PID of the position on top of it.
In level 1, I have 'General Manager' and 'Supervisor'.
In level 2, under 'General Manager(PID: 1)' : 'Asst. Manager', under 'Supervisor(PID: 2)' : 'Marketing'.
In level 3, under 'Asst. manager(PID: 3)' : 'Sales' & 'Purchase', under 'Marketing(PID:2) : none.
+-----+-----------------+-----------+-----------+
| PID | pos_name | pos_level | pos_under |
+-----+-----------------+-----------+-----------+
| 1 | General Manager | 1 | 0 |
| 2 | Supervisor | 1 | 0 |
| 3 | Asst. Manager | 2 | 1 |
| 4 | Sales | 3 | 3 |
| 5 | Purchase | 3 | 3 |
| 6 | Marketing | 2 | 2 |
+-----+-----------------+-----------+-----------+
Now how do I make the query so I get a nested array as the result like this:
Array
(
[0] => Array
(
[pos_level] => 1
[pos_name] => General Manager
[pos_under] => Array
(
[0] => Array
(
[pos_level] => 2
[pos_name] => Asst. Manager
[pos_under] => Array
(
[0] => Array
(
[pos_level] => 3
[pos_name] => Sales
)
[1] => Array
(
[pos_level] => 3
[pos_name] => Purchase
)
)
)
)
)
[1] => Array
(
[pos_level] => 1
[pos_name] => Supervisor
[pos_under] => Array
(
[0] => Array
(
[pos_level] => 2
[pos_name] => Marketing
[pos_under] => Array
(
)
)
)
)
)
I have tried using multiple queries and using array_push using the results, but I have like around 100+ pos_name and I think it is messy, I have also tried using loop to keep running queries for each level and under, also tried using multiple tables for each level, but I am hoping I can use only 1 table and able to query the result as the nested array above for further use in my application.
All answers, comments, and suggestions are very welcomed. Thank you.
As mentioned above in the comments I doubt in general that the approach you are following is a good one. That is because it will not scale! You try to take all entries from your database and pack them into a single, hierarchical array. That means you create several copies of each entry in memory. What will happen with a growing number of entries? You face a constantly raising memory consumption of your script which will obviously make it fail ultimately.
Nevertheless I accepted the challenge and implemented a small demonstration of how to cleverly construct such nested structures with the help of references. Such references not only simplify the creation of nested structures, they also reduce the memory footprint by preventing that entries are copied by value again and again. This however will not solve the general scaling issue with this approach mentioned above, it can only help to reduce it.
I also took the liberty to make a small modification to your approach and introduce a new property "pos_over" to hold entries under an entry. Two reasons for that:
it usually is not a good idea to remove original available data and especially not to replace it with an altered meaning
the meaning of the term "pos_under" is to describe under what other entry an given entry is (to be) placed. But from the "upper" entries point of view the ones "below" it should not be referenced by "pos_under", right? That would contradict the original meaning of that term.
The following code does not depend on a database for demonstration purpose. Instead it reads the raw data from a CSV string and parses that. The actual building of the desired structure structure is marked further down by a comment. Also it should be mentioned that the code expects the original data to reference other entries only after they have been declared. So if processed from top to bottom each entry under another one can expect that other one to already exist.
Note, that the actual code to build that nested structure consists of only a mere 12 clever lines...
<?php
// the raw CSV data
$csvText = <<<CSV
PID|pos_name|pos_level|pos_under
1|General Manager|1|0
2|Supervisor|1|0
3|Asst. Manager|2|1
4|Sales|3|3
5|Purchase|3|3
6|Marketing|2|2
CSV;
// praparation of CSV data
foreach (explode("\n", $csvText) as $csvRow) {
$csvData[] = str_getcsv($csvRow, '|');
}
$csvTitle = array_shift($csvData);
$table = [];
foreach ($csvTitle as $titleKey=>$titleValue){
foreach ($csvData as $csvRow=>$csvColumn) {
foreach ($csvColumn as $csvKey=>$csvValue) {
$table[$csvRow][$csvTitle[$csvKey]] = $csvValue;
}
}
}
// creation of the structure
$catalog = [];
$structure = [];
foreach ($table as $key=>&$entry) {
$entry['pos_over'] = [];
if ($entry['pos_under'] == 0) {
$structure[] = &$entry;
$catalog[$entry['PID']] = &$structure[count($structure)-1];
} else {
$catalog[$entry['pos_under']]['pos_over'][] = &$entry;
$catalog[$entry['PID']] = &$catalog[$entry['pos_under']]['pos_over'][count($catalog[$entry['pos_under']]['pos_over'])-1];
}
}
// demonstration output
print_r($structure);
The output of above experiment is:
Array
(
[0] => Array
(
[PID] => 1
[pos_name] => General Manager
[pos_level] => 1
[pos_under] => 0
[pos_over] => Array
(
[0] => Array
(
[PID] => 3
[pos_name] => Asst. Manager
[pos_level] => 2
[pos_under] => 1
[pos_over] => Array
(
[0] => Array
(
[PID] => 4
[pos_name] => Sales
[pos_level] => 3
[pos_under] => 3
[pos_over] => Array
(
)
)
[1] => Array
(
[PID] => 5
[pos_name] => Purchase
[pos_level] => 3
[pos_under] => 3
[pos_over] => Array
(
)
)
)
)
)
)
[1] => Array
(
[PID] => 2
[pos_name] => Supervisor
[pos_level] => 1
[pos_under] => 0
[pos_over] => Array
(
[0] => Array
(
[PID] => 6
[pos_name] => Marketing
[pos_level] => 2
[pos_under] => 2
[pos_over] => Array
(
)
)
)
)
)

Howto make this relation work in MYSQL or Laravel

I'm no amazing with MYSQL at all, however laravel framework has made it very easy for me to get what i need as long as i know the basics.
So this question will first aim towards the MYSQL people, because i would rather figure out how to achieve this in plain MYSQL, and then convert it into laravel queries after.
I have 4 tables that need to be used in this query, as seen below:
1. products
id | name | description | price
2. customers
id | fname | lname | email | telephone
3. orders
id | customer_id | total_price | status
4. order_items
id | order_id | product_id | quantity | price
So i am creating an orders page on my web application. On this page it will show a list of all orders, including the order_items to that particular order. It will also include which customer this order belongs to.
I have managed to achieve the above using laravel, and i get the array seen below:
Array
(
[0] => Array
(
[id] => 9
[customer_id] => 16
[total_price] => 103.96
[status] => new
[created_at] => 2016-02-24 03:06:41
[customer] => Array
(
[id] => 16
[fname] => firstname
[lname] => lastname
[email] => firstname.lastname#gmail.com
[telephone] => 07707707707
[address_line_1] => Warstone Rd, walsall
[address_line_2] => Wolverhampton
[postcode] => WV10 7LX
)
[order_item] => Array
(
[0] => Array
(
[id] => 1
[order_id] => 9
[product_id] => 44
[quantity] => 1
[price] => 50.00
)
[1] => Array
(
[id] => 2
[order_id] => 9
[product_id] => 46
[quantity] => 2
[price] => 31.98
)
[2] => Array
(
[id] => 3
[order_id] => 9
[product_id] => 48
[quantity] => 1
[price] => 7.99
)
[3] => Array
(
[id] => 4
[order_id] => 9
[product_id] => 51
[quantity] => 1
[price] => 13.99
)
)
)
)
Now the part i am having trouble with is getting the products that relate to the order_items.
So far it has worked for me because i have been doing thinking like this
$order = Order::find($id)->with('customer','orderItem')->get()->toArray();
This works easy because an order has a customer_id field and an order_items has an order_id. But for me to get the products i need to join products to order_items.
If any one is good at MYSQL and can provide me a query to study and then convert into laravel that would be great.
If anyone knows laravel 5, well this is all the laravel stuff below:
Order.php
public function customer(){
return $this->belongsTo('App\Customer');
}
public function orderItem(){
return $this->hasMany('App\OrderItem');
}
OrderItem.php
public function order(){
$this->belongsTo('App\Order');
}
public function product(){
$this->hasOne('App\Product');
}
Product.php
public function orderitem(){
$this->hasOne('App\OrderItem');
}
Customer.php
public function orders(){
$this->belongsTo('App\Order');
}
As you can see above are my modal relationships i have set up.
This is my controller where i try to get the full array.
public function show($id)
{
$order = Order::find($id)->with('customer','orderItem','product')->get()->toArray();
echo "<pre>";
print_r($order);
echo "</pre>";
}
The error i receive is:
call to undefined method Illuminate\Database\Query\Builder::product()
If i remove the ->with('customer','orderItem','product') and change it to ->with('customer','orderItem') i get the array posted above.
Does anyone know how i can achieve this please?
You are on the right part the only mistake you are doing is you are calling product on the order model which has no direct relation with it. You have to call the product model through the orderitem model like this
Order::find($id)->with('customer','orderItem.product')->get()->toArray()

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'];
}

Optimizing multiple queries in MySQL and PHP

Questions
How should I do the query(ies) to get this results?
Should I use a different structure for database tables?
Details
I want to get results from 3 tables:
+------------------------------+-------------------+
| courses | id | <-------+
| | name | |
| | | |
+------------------------------+-------------------+ |
| sections | id | <-------|----------+
| | course_id | <- FK(courses.id) |
| | name | |
+------------------------------+-------------------| |
| resources | id | |
| | section_id | <- FK(sections.id)-+
| | name |
+------------------------------+-------------------+
I want to store results in a PHP Array like this:
Array
(
[courses] => Array
(
[id] => 1
[name] => course 1
[sections] => Array
(
[0] => Array
(
[id] => 1
[course_id] => 1
[name] => course 1 section 1
[resources] => Array
(
[0] => Array
(
[id] => 1
[section_id] => 1
[name] => resource 1
)
)
)
)
)
)
EDIT
What I did:
$cources = DB::query(Database::SELECT,
'select * from courses')->execute($db,false)[0]; // Get all courses as array
foreach($courses as &$course) {
$sections = DB::query(Database::SELECT,
'select * from sections where course_id = '.$courses['id']);
$course['sections'] = $sections;
foreach($course['sections'] as &&section) {
$resources = DB::query(...); // Get array of resources
$section['resources'] = $resources;
}
}
The database structure is normalized - this is correct and should not be changed.
However, SQL returns de-normalized or "flattened" data for an N+ join: only a set of homogenous records can be returned in a single result-set. (Some databases, like SQL Server, allow returning structure by supporting XML generation.)
To get the desired array structure in PHP will require:
Separate queries/result-sets (as shown in the post): ick!
There will about one query/object. While the theoretical bounds might be similar, the practical implementation will be much less efficient and the overhead will be much more than for single query. Remember that every query incurs (at the very least) a round-trip penalty - as such, this is not scalable although it will likely work just fine for smaller sets of data or for "time insensitive" operations.
Re-normalize the resulting structure:
This is very trivial to do with support of a "Group By" operation, as found in C#/LINQ. I am not sure how this would be approached [easily] in PHP1. This isn't perfect either, but assuming that hashing is used for the grouping, this should be able to scale fairly well - it will definitely be better than #1.
Instead of the above, consider writing the query in such a way that the "flat" result can be used within the current problem/scope, if possible. That is, analyze how the array is to be used - then write the queries around that problem. This is often a better approach that can scale very well.
1 Related to re-normalizing the data, YMMV:
SQL result to PHP multidimensional array
PHP array to multidimensional array
Group a multidimensional array by a particular value?
You can try something like this
SELECT * FROM (
select c.id, c.name from courses c
union
select s.id, r.name,s.course_ID from sections s
union
select r.id, r.name,r.section_ID from resources r
)
You cant get multi dimensional result from mysql. The query for getting the elements should be like this:
select courses.id as coursesId,courses.name as coursesName,sections.id as sectionsId,sections.name as sectionsName,resources.id as resourcesId, resources.name as resourcesName
from courses
left join sections on courses.id=sections.course_id
left join resources on sections.id=resources.section_id;
But ofcourse it will not give you the array as you like.
if you are familiar with php then you can use this code i am writing only 2nd level you can write same way with third label
$final=array();
$c=-1;
$cid=false;
$cname=false;
$query = "SELECT c.*,s.*,r.* FROM courses AS c LEFT JOIN sections AS s ON c.id=s.course_id LEFT JOIN resources AS r ON r.section_id =s.id";
$result=mysql_query($query, $this->con) or die(mysql_error());
while($row= mysql_fetch_array($result)){
if($cid!=$row[2]){
$final['cources'][++$c]['id']=$cid=$row[0];
$final['cources'][$c]['name']=$cname=$row[1];
$s=-1;
}
$final['cources'][$c]['sections'][++$s]['id']=$row[2];
$final['cources'][$c]['sections'][$s]['course_id']=$row[3];
$final['cources'][$c]['sections'][$s]['name']=$row[4];
}
echo "<pre>";
print_r($final);
echo "</pre>";
//Outpur
Array
(
[cources] => Array
(
[0] => Array
(
[id] => 1
[name] => c1
[sections] => Array
(
[0] => Array
(
[id] => 1
[course_id] => 1
[name] => s1-1
)
[1] => Array
(
[id] => 1
[course_id] => 1
[name] => s1-1
)
)
)
[1] => Array
(
[id] => 2
[name] => c2
[sections] => Array
(
[0] => Array
(
[id] => 2
[course_id] => 2
[name] => s1-2
)
)
)
)
)

Insert Array values, multiple rows

I'm trying to record some information on a database. My post looks like this:
Array
(
[Action] => 1000
[Date_Stat] => 07/02/2013
[Date_Final] => 07/02/2013
[Product_Id] => Array
(
[0] => 2
[1] => 6
[2] => 1
)
[Conversion] => Array
(
[0] => 1,20
[1] => 1,00
[2] => 2,03
)
[ValueMin] => Array
(
[0] => 2,00
[1] => 1,58
[2] => 2,70
)
[ValueMax] => Array
(
[0] => 2,50
[1] => 1,98
[2] => 2,90
)
[ValueMedio] => Array
(
[0] => 2,20
[1] => 1,68
[2] => 2,80
)
)
HOW can I insert all this on database the right way?
I'm not sure about the best way to design the tables and store the information. I'm using this to make a PRICE TABLE with starting date, final date and list all products with prices.
Also I'm thinking what is the best method. There are 2 possibilities I think about
Date_Start | Date_End |Product_Id | ValueMin | ValueMax | ValueMedio | Conversion
02-02-2013 02-03-2013 1 1.00 2.00 3.00 4.00
02-02-2013 02-03-2013 2 1.00 2.00 3.00 4.20
02-02-2013 02-03-2013 3 1.00 2.00 2.00 4.40
OR (using implode and putting all values on the same row)
Date_Start | Date_End |Product_Id | ValueMin | ValueMax | ValueMedio | Conversion
02-02-2013 02-03-2013 1,2,3 1,1,1 2, 2,2 3,3,2 4, 4.3, 4.4
Thanks a lot!
Choose the option mentioned first. Selecting Rows will become much easier if you do it that way.
To insert the records, use a simple prepared Statement (PHP Manual) and use a for-Loop.
I'd suggest a little tweak over the first option. If you create a separate table (Something along the lines of "Prices") like this:
id|DateStart|DateEnd|
1|02-02-2013|02-02-2013|
And then, in the table you suggested, you'd replace the date range for the PriceId (Foreign Key to this table). That way it'll be easier for you to maintain the consistency over changes on date ranges.

Categories