Display grouped sql results - php

I have a sql query that groups results. The print_r shows the results I would like are there. Now I would like to display these results in table groups i.e. Table One with a list of all the seats with that table, Table Two etc.
I have tried all kinds of things to get this done to no avail... here is the code. I can easily display the records - but would like to display them by groups arghhh
$seatings = $wpdb->get_results("SELECT
bb_cl_seating.table,
bb_cl_seating.seat,
bb_cl_seating.seat_id,
bb_events_attendee.fname,
bb_events_attendee.lname,
bb_events_attendee.email
FROM bb_cl_seating
LEFT JOIN bb_events_attendee
ON bb_cl_seating.id = bb_events_attendee.id
WHERE bb_cl_seating.event_id = '1' ");
foreach ($seatings as $seating) {
} // Ends foreach

$seatings = $wpdb->get_results("SELECT
bb_cl_seating.table,
bb_cl_seating.seat,
bb_cl_seating.seat_id,
bb_events_attendee.fname,
bb_events_attendee.lname,
bb_events_attendee.email
FROM bb_cl_seating
LEFT JOIN bb_events_attendee
ON bb_cl_seating.id = bb_events_attendee.id
WHERE bb_cl_seating.event_id = '1' ");
foreach ($seatings as $seating => $group) {
//$data[table] = seat,seat2,seat3...
$data[$group[1]] = $data[$group[1]].','.$group[2];
} // Ends foreach
In this example create one array $data of tables with yours seats sort by ','.
Its help?

This did the trick - hope it helps someone else:-)
$seatings = $wpdb->get_results("SELECT bb_cl_seating.table, bb_cl_seating.seat, bb_cl_seating.seat_id, bb_events_attendee.fname, bb_events_attendee.lname, bb_events_attendee.email
FROM bb_cl_seating
LEFT JOIN bb_events_attendee ON bb_cl_seating.id = bb_events_attendee.id
WHERE bb_cl_seating.event_id = '1'
ORDER BY bb_cl_seating.table, bb_cl_seating.seat
");
$table_title = '';
foreach($seatings as $result => $col) {
if($table_title !== $col->table) {
$table_title = $col->table;
echo "<strong>$table_title</strong>";
echo "<br />";
}

Related

PHP/SQL: Faster Way to Combine Query Results

I'm joining data from two SQL queries and I'm wondering if there is a faster way to do this as a single SQL query because there is a lot of looping involved. I've got two queries that look for different string values in the "option_name" field:
$sql01= "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name = 'wpm_login_date' ORDER BY user_id";
$sql02 = "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name ='stripe_cust_id' ORDER BY user_id ";
Then I create two arrays:
//Process the 1st SQL query data into an Array
$result_array01 = array();
$j = 0;
while($r = mysql_fetch_assoc($result01)) {
if(!empty($r['option_value'])){
//User Id and Last Login
$result_array01[$j]['user_id'] = $r['user_id'];
$result_array01[$j]['last_login'] = $r['option_value'];
$j++;
}
}
//Process the 2nd SQL query data into an Array
$result_array02 = array();
$k = 0;
while($s = mysql_fetch_assoc($result02)) {
if(!empty($s['option_value'])){
//User Id and Stripe Customer Id
$result_array02[$k]['user_id'] = $s['user_id'];
$result_array02[$k]['cust_id'] = $s['option_value'];
$k++;
}
}
And finally, I combine the arrays:
//Combine the SQL query data in single Array
$combined_array = array();
$l = 0;
foreach($result_array01 as $arr01){
// Check type
if (is_array($arr01)) {
//mgc_account_print("hello: " . $arr01['user_id'] . "\r\n");
foreach($result_array02 as $arr02){
// Check type
if (is_array($arr02)) {
//Check if User Id matches
if($arr01['user_id'] == $arr02['user_id']){
//Create Array with User Id, Cust Id and Last Login
$combined_array[$l]['user_id'] = $arr01['user_id'];
$combined_array[$l]['last_login'] = $arr01['last_login'];
$combined_array[$l]['cust_id'] = $arr02['cust_id'];
$l++;
}
}
}
}
}
Why you doing in two different queries?
Use mysql IN('val', 'val2');
$sql01= "SELECT tbl1.user_id, tbl1.option_value FROM wp_wlm_user_options as tbl1 WHERE tbl1.option_name = 'wpm_login_date'
union all
SELECT tbl2.user_id, tbl2.option_value FROM wp_wlm_user_options as tbl2. WHERE tbl2.option_name ='stripe_cust_id' ";
But using OR/AND will your help you in your case , I didnt see at first that you want combined same table. I didnt delete my answer to help you for another solution
Also you should use DISTINCT to avoid multiple records.
SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE

Displaying 5 rows of data from query

I have a simple table (mgap_orders) with customer orders in it. Multiple have the the same id (mgap_ska_id) and I simply want to pull 5 records from the table and display all five.
I can easily get one record with the following query and PDO, but how can I display 5 rows instead of only one row?
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id";
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$item=$row_cat_sub['mgap_item_description'];
$item_num=$row_cat_sub['mgap_item_number'];
$item_type=$row_cat_sub['mgap_item_type'];
$item_cat=$row_cat_sub['mgap_item_catalog_number'];
$item_ven=$row_cat_sub['mgap_item_vendor'];
$item_pur=$row_cat_sub['mgap_item_percent_purchased'];
$item_sales=$row_cat_sub['mgap_item_sales'];
}
Use limit 5 then put the results in an array, like this:
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id LIMIT 5";
$items = array();
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$items['item'] = $row_cat_sub['mgap_item_description'];
$items['item_num'] = $row_cat_sub['mgap_item_number'];
$items['item_type'] = $row_cat_sub['mgap_item_type'];
$items['item_cat'] = $row_cat_sub['mgap_item_catalog_number'];
$items['item_ven'] = $row_cat_sub['mgap_item_vendor'];
$items['item_pur'] = $row_cat_sub['mgap_item_percent_purchased'];
$items['item_sales'] = $row_cat_sub['mgap_item_sales'];
}
Then you can do:
foreach($items as $item) {
// echo $item['item'] or whatever
}
EDIT: Or you can skip putting them in the array and just use the while() to do what you need to do with the data.

PHP inserting array into an object

I am trying to inject an array into an object but it's just not working. This is what I am doing:
1) Get a specific Match record from the database
2) Get all the Player records from the database that are associated with that match
3) Add them players to the Match object
Code:
$matchQuery = "SELECT * FROM matches where new = 1 order by date asc limit 1";
$matchResult = mysql_query($matchQuery,$link) or die('Errant query: '.$matchQuery);
/* create one master array of the records */
$matches = array();
if(mysql_num_rows($matchResult)) {
while($match = mysql_fetch_assoc($matchResult)) {
$playersQuery = "SELECT p.* FROM match_players mp
LEFT JOIN players p on p.id = mp.player_id
WHERE mp.match_id = '$match->id'";
$playerResult = mysql_query($playersQuery,$link) or die('Errant query: '.$playersQuery);
$players = array();
if(mysql_num_rows($playerResult)) {
while($player = mysql_fetch_assoc($playerResult)) {
$match->players[] = $player; //<-- This doesn't seem to work
}
}
$matches[] = $match;
}
}
The objects within Match are being spat out, BUT, the Players are not.
$match is an array, the result of the deprecated mysql_fetch_assoc(). So $match->players[] = $player; is not going to work.
If there is no players key in the sql result, you can add it to the array:
$match['players'][] = $player;
Otherwise you would have to use a different key.
Another problem is your query in the loop: You use $match->id and that should be $match['id'] as $match is an array.
By the way, doing sql queries in a loop is never a good idea, you should try to get your results in one query joining the different tables.
$match["players"] = array();
while($player = mysql_fetch_assoc($playerResult)) {
$match["players"][] = $player;
}

Queries with conditional queries

Let's say i have a query with quite a number of joins and subqueries in one php file that handles queries.
Nb: i put an example of what $query looks like at the bottom
$query = query here;
if ($query) {
return $query->result();
} else {
return false;
}
}
Then in my php file that handles the html, i have the usual foreach loop with some conditions that require making other queries e.g;
Note: result houses object $query->result().
foreach ($results as $item) {
$some_array = array();
$some_id = $item->id;
if ($some_id != 0) {
//id_return_other_id is a function that querys a db table and returns the specified column in the same table, it returns just one field
$other_id = id_return_other_id($some_id);
$some_query = another query that requires some joins and a subquery;
$some_array = the values that are returned from some_query in an array
//here i'm converting obj post into an array so i can merge the data in $some_array to item(Which was converted into an array) then convert all of it back into an object
$item = (object)array_merge($some_array, (array)$item);
}
//do the usual dynamic html stuff here.
}
This works perfectly but as i don't like the way i'm doing lot's of queries in a loop, is there a way to add the if $some_id != 0 in the file that handles queries?
I've tried
$query = query here;
//declaring some array as empty when some_id is 0
$some_array = array();
if ($query) {
if ($some_id != 0) {
//same as i said before
$other_id = $this->id_return_other_id($some_id);
$some_query = some query;
$some_array = array values gotten from some query;
}
$qresult = (object)array_merge($some_array, (array)$query->result);
return $qresult;
} else {
return false;
}
}
This doesn't work for obvious reasons, does any one have any ideas?
Also if there's a way to make these conditions and queries in the $query itself i'd love you forever.
Ps: A demo query would be something like
$sql = "SELECT p.*,up.*,upi.someField,etc..
FROM (
SELECT (another subquery)
FROM table1
WHERE table1_id = 3
UNION ALL
SELECT $user_id
) uf
JOIN table2 p
ON p.id = uf.user_id
LEFT JOIN table3 up
ON .....
LEFT JOIN table4
ON ....
LEFT JOIN table5
ON ....
And so on..etc..
ORDER BY p.date DESC";
$query = mysql_query..
It seems like you just need to run two queries in your query file. The first query would get a broad set of what you’re looking for. The second query would query an id that’s in the result and perform a new query to get any details about that particular id. I use something similar to this in the customer search page for my application.
$output = array();
$query1 = $this->db->query("SELECT * FROM...WHERE id = ...");
foreach ($query->result_array() as $row1)
{
$output[$row1['some_id']] = $row1;
$query2 = $this->db->query("SELECT * FROM table WHERE id = {$row1['some_id']}");
foreach ($query2->result_array() as $row2)
{
$output[$row1['some_id']]['data_details'][$row2['id']] = $row2;
}
}
Then in your page that displays html, you’ll just need two foreaches:
foreach($queryresult as $key=> $field)
{
echo $field['some_field'];
foreach($child['data_details'] as $subkey => $subfield)
{
echo $subfield['some_subfield'];
}
}
I know you’re using objects, but you could probably convert this to use that format. I hope this makes sense/helps.
use this
if ($some_id !== 0) {
instead of
if ($some_id != 0) {

slow results using while loop with mysql_fetch_array

I'm getting terribly slow results from the following code. I've been trying to troubleshoot it for hours but with no results. I've included only the relevant code.
Edit:
I am trying to select an id from a database and then use that id to get all the images associated with it. I am then narrowing that group of images down to one. Once I have that image I am resizing it through an external file.
I've tried removing various parts of the code to identify the problem and it seems as if the slow down is being caused by the second query but I am not sure why. Thanks for your help.
$getworks = mysql_query ("SELECT a_id from artists where display_works = '1' and active = '1' order by project_year desc, fullname desc");
while ($getworksrow = mysql_fetch_assoc($getworks)){
$totalimages=1;
$addstyle = "";
$id = $getworksrow["a_id"];
$getimages = mysql_query ("SELECT a_id, image_id from images where a_id = '". $id ."' order by position asc LIMIT 1");
$getimagesrow = mysql_fetch_assoc($getimages);
foreach ($getimagesrow as $getimagesrows){
extract($getimagesrow);
if($totalimages > 1){ $addstyle = 'style="display:none;"'; }
else {
$myimagename = "http://artist.com/$a_id/images/$image_id" . "_large.jpg";
list($width, $height, $type, $attr) = getimagesize("$myimagename");
$myimagename = "http://artist.com/artists/resize.php/$a_id/images/$image_id" . "_large.jpg?resize(157x2000)";
if($getworksrows["layout"] == "vert"){$pl = "_vertical";}else if($getworksrows["layout"] == "website"){$pl = "-s";}else if($getworksrows["layout"] == "video"){$pl = "_video";}else{$pl = "_horizontal";}
echo "<li class='thumbnail_container' $addstyle> <a class='thumbnail' href=\"../works$pl.php?a_id=" . $getworksrows["a_id"] . "\"><span><img src=\"$myimagename\" /></span>\n</a></li>\n";
}
$totalimages++;
}
}
It's a a big performance overhead to execute queries like this specially when parent query have large no. of records.
You should use join artists table with images table and get all data by single query.
Later on make 2D array of per artists and images. and loop according to 2D array to display data
Below is join query you should use:
SELECT * from artists as art
left join images as img on art.a_id=img.a_id
where display_works = '1' and active = '1'
order by project_year desc, fullname desc
In While make data array:
while ($getworksrow = mysql_fetch_object($getworks)){
$data['a_id']['img_id']=$getworksrow->image; //Make 2D array
........
........
}
looping and display data :
foreach($data as $id=>$images)
{
foreach($images as $val){
// Do your stuff for displaying data
}
}
So please do required changes.

Categories