PHP - Group Concat
im trying to pull the information for a post which is to include 3 db tables(posts, users, attachments)
Ive tried the following code: Code: [Select] $query = $link->query("SELECT p.*, u.u_username, u.u_posts, u.u_avatar, u.u_signature, u.u_avatar_cropped, group_concat(a.a_name, a.a_size, a.a_date_posted separator '<br />') attachments FROM ".TBL_PREFIX."posts as p JOIN ".TBL_PREFIX."users as u ON (u.u_username = p.p_poster) LEFT JOIN ".TBL_PREFIX."post_attachments as a USING (".TBL_PREFIX."posts.p_pid) WHERE p.p_tid = '$tid' GROUP BY p.p_pid ORDER BY p.p_time_posted ASC")or die(print_link_error()); but that generates the error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.p_pid) WHERE p.p_tid = '158' GROUP BY p.p_pid ORDER BY p.p_time_pos' at line 10" All i am trying to do is pull everything from posts, join users and select all attachments that belong to the post. Here is my database setup(shortened) asf_posts p_pid | p_name | p_poster 1 test doddsey65 asf_users u_uid | u_username 1 doddsey65 asf_attachments a_aid | a_pid | a_name 1 1 name can anyone help? Similar TutorialsI have an existing two table structure where sub-data is related to main data in a many-to-one relationship.
There are several identically named columns in both tables.
(The PHP database class will return an associative array that did not deal with identical keys in the row.)
I'm LEFT JOINing the sub-data to the main-data tables.
When using a stand-alone query browser (to experiment), the display shows all columns, even those column names that appear more than once in the row.
Is there a general approach to making keys (column names) unique strictly using a MySQL SELECT statement?
Perhaps using table aliases, how can I concat the alias to the columns that come from each table?
What I am trying to avoid is giving an alias to each column in a list of column names, such as:
SELECT
C.name AS C_name
C.numb AS C_numb
D.name AS D_name
D.numb AS D_numb
etc.
I am wanting more like the result one could guess would be from:
C.* AS C_*
D.* AS D_*
Or better:
* AS CONCAT(__TABLE__, '_', *)
if __TABLE was a magic constant (like PHP's __LINE__, __FILE__, etc).
What I'm trying to do is allow people to change the order of their navigation bar. I don't have a problem doing this using a listbox to move the values up and down. But to start me off, I'd like to know how I can use CONCAT or explode to draw data from the DB and list it. To better understand: I have a database with a table called "navbar". I have the fields: ID, name, link, icon, caption What we'll be looking at most is the ID. The ID's range from 1-19, so 19 links on the navbar. They are extracted from the database like so: $navbar=$db->execute("select * from navbar"); for($i=1;$nav=$navbar->fetchrow();$i++) { $name=$nav['name']; $link=$nav['link']; $title=$nav['caption']; $image=$nav['icon']; ?> <tr> <td background="images/sub_btn.gif" class="norepeat" valign=top> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td></td> <td><img src="images/spacer.gif" width="198" height="1"></td> </tr> <tr> <td><img src="images/spacer.gif" width="1" height="19"></td> <td style="padding-left: 10px;" class=sub><img src=<?=$image?> width=13 height=13 align=absmiddle> <a target=middle href="<?=$link?>" class="sub_lnk" title='<?=$title?>'><?=$name?></a> </td> </tr> </table></td> </tr> <?}?> This is for my online game, so we then go to my players table and add a field called "navorder". The default value is: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 How would I, just for tests, lists the values from the navbar table, by ID, on the page? Example: My value is set to 1,2,3,4,5 When drawing the data, however I do it, would show: Link1 Link2 Link3 Link4 Link5 Now if I changed the order, with a listbox which I can do, would change it to 3,1,5,2,4 It would then show: Link3 Link1 Link5 Link2 Link4 Sorry if it seems confusing, I tried my best at explaining it. Someone told me to use the explode function, or CONCAT. I tried to read up on explode() but just got confused as to how to use it. If someone could tell me how to do this it'd be much appreciated Thanks! Hi all, Hi all, does anyone know how to perform this, or if it's even possible? I need every 6th row to be a GROUP BY of the following 5 rows, they all share a common group_id so that's what the GROUP BY is performed on. 1. GROUP BY group_id 2. item #1 3. item #2 4. item #3 5. item #4 6. item #5 7. GROUP BY group_id 8. item #6 ... and so on I am trying to get a group by to work but for some reason it will only display one output. Not sure what the problem is. Code: [Select] mpid mpyear mpmonth mpday mptitle 4 2012 3 2 Text stuff here 3 2012 3 1 Day 1 stuff here 2 2012 2 28 Feb stuff here 1 2011 12 27 First post test here So what I am trying to do is sort out per year month ie: 2012 3 Text stuff here Day 1 stuff here 2 Feb stuff here 2011 12 First post test here That is what I eventually want it to look like, but first thing I need to do is get atleast the mptitle to group first. Code: [Select] $query = "SELECT * FROM monsterpost group BY 'mpmonth'"; $result = mysql_query($query) or die(mysql_error()); // Print out result while($row = mysql_fetch_array($result)){ echo $row['mptitle']; echo "<br />"; } ?> Hi, I have database, screenshot attached. I have to print all records of attendance sort by ID and have sum group by ID. How to know or figure out when the ID changes so that i can show the total for that ID. Bare with me please and try to show me where is my mistake! Code: <?Php include('session.php'); include('dbcon.php'); ?> <html> <head> <link rel="stylesheet" type="text/css" href="bootstrap.css"> </head> <body> <div class="container"> <div class="row"> <div class="col m-auto"> <div class="card mt-5"> <table class="table table-bordered"> <tr> <input type="button" onClick="window.print()" value="Print The Report"/> <td>OracleID</td> <td>Name</td> <td>Designation</td> <td>Clocking In Time</td> <td>Clocking Out Time</td> <td>Duration</td> </tr> <?php $isdone = -1; $query = "select * from attendance_records where isdone= '".$isdone."' order by OracleID"; $result = mysqli_query($con, $query); $query2 = "SELECT sec_to_time(SUM(timestampdiff(SECOND, ClockingInDate, ClockingOutDate))) as total from attendance_records group by OracleID"; $result2 = mysqli_query($con, $query2); while ($row = mysqli_fetch_assoc($result)) { $userid = $row['OracleID']; $name = $row['Name']; $des = $row['Des']; $clockingindate = $row['ClockingInDate']; $clockingoutdate = $row['ClockingOutDate']; $duration = $row['Duration']; $t=time(); $curdate = date("d-m-Y",$t); $curTime = date("g:i:s A",$t); ?> <tr> <td><?php echo $userid ?></td> <td><?php echo $name ?></td> <td><?php echo $des ?></td> <td><?php echo $clockingindate ?></td> <td><?php echo $clockingoutdate ?></td> <td><?php echo $duration ?></td> </tr> <?php } while($row2 = mysqli_fetch_assoc($result2)) { $totals= $row2['total']; echo '<td><h5>Total Attendance Time:</h5></td>'; echo '<td>'; echo $totals; echo '</td>'; } echo '<tr>'; echo 'Report created by ', $_SESSION['user_id2'], ' on ', $curdate, ' at ', $curTime; echo '</tr>'; ?> </table> <a href="home.php" width="100%">Click here to go back to Main Menu</a> </div> </div> </div> </div> </body> </html> and screenshot of result is attached. I have the totals but not at the end of each OracleID, it is at the end of the report. Thanks.
Hi
I am reading in data from a csv file
if (($handle = fopen("data.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { echo "User Name: $data[0]"; echo "Booking IDs: $data[1]"; } echo "<hr>";The problem is some of the usernames are duplicated so get outputted the same user name 20 times but with different IDs, obviously but I am unsure how to group them together. I can't seem to figure out how to write if the next username is the same as current then just add another ID not go through the entire loop. Any ideas? Thanks This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=353968.0 G'day to all, I need some help building a site that has the ability to accept members and deposit those members in a database. When the members join they will have the ability to add features to their profile; like, skills and certificates. Upload pictures of certificates and a profile pic. The admin area needs to have the ability to add membership types and give those members specific abilities. The admin also needs to have the ability to create profile options, like additional skills. Like a type 1 member has the ability search and see all type 2 members who have a particular skill set. type 2 members just get to see their own profile and the tasks the type 1 members list.
This all might sound like a bunch of brambles but please let me know if you are interested and we can get more involved. Thank you so very much for your help in advanced... Juan This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306114.0 Hi Just a quick one. I want my output result to look like this. In its simplistic form I have 2 columns, NAME and NUMBER. Adam 1 2 3 Becky 1 2 3 Charlie 1 2 3 So the output results are grouped by the "name" field, then ordered by the "number" field. I thought it was GROUP BY, but that function is something else. Iv tried searching around but im unsure what you call this form of grouping results. Many Thanks! Hi, Cut down code SELECT count(number) FROM table GROUP BY title echo $title .'<br>'. $number; That outputs Code: [Select] Title1 5 Title2 9 Title3 2 But what do i do if i wanted to retain and loop through the "$number" actual values, not JUST count the total? I still need access to what "$number" is while looping. But as GROUP BY returns one result.. im stuck. Ideally i want this as the resulting output Code: [Select] title1 // grouped title 3 // total number of $numbers per grouped title 1234 12345 123456 // The actual values of $number totalling to the above grouped number title2 // grouped title 2 // total number of $numbers 1234 123456 // The actual values of $number totalling to the above grouped number I have a table that has pairs of matching records that are identified as matching on a specific column. In other words, 2 users submit data on the same record, and they are identified as matching and belonging to the same record data because the table column gameid is the same for the pair. How can I output the information for the pair of matching records for each of these into a table repeating it until Ive looped through all records? In other words I want to create 1 table with headers for each matching pair all the way down... thanks in advance. Hi all, I have a script that is essentially a log file of all preious versions of an article (versioning) You can see the script I am talking about in action at: http://danielrhyshardy.com/AWT/forumadmin.php What I would like to do is, instead of displaying the title of each instance (you will see there are two instances named "apple", as they are two previous versions of an article), I would like to display that title once, and then all of the instances of that title be displayed below. I hope that makes sense. Here is the code Code: [Select] <? $sql = "SELECT id,title,message,date_added FROM messages2 ORDER BY id "; $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR); while(list($id,$title,$message,$date_added)=mysql_fetch_row($result)){ echo '<div style="color:#bb0000;width:250px;text-align:center;float:left;margin-left:15px;margin-bottom:15px;padding-bottom:20px;"><b>'.$title.'<br>'.$date_added.'</b> <input id="'.$message.'" type="radio" name="admin[]" value="'.$id.'" onclick="javascript:document.form22.car.value=this.id" > </font></div>'."\n"; } ?> I would use something like Code: [Select] if ($title = "apple") { but this would obviously not work for new posts, unless I wanted to constantly update my code. I am sure there is a simple way to achieve this. Perhaps someone can tell me!? Thanks in advance Dan Hi All, I hope i'm posting in the right place but also hope someone can help! I've got the following code: <?php $variations = $product->get_available_variations(); if ($variations): ?> <div class="table-responsive"> <table class="table table-striped"> <tbody> <?php foreach ($variations as $key => $value) : ?> <tr> <td><?php echo $value['sku']; ?> <?php echo $value['variation_id']; ?></td> <?php foreach ($value['attributes'] as $attrKey => $attr) : $tax = str_replace('attribute_', '', $attrKey); $term_obj = get_term_by('slug', $attr, $tax); ?> <td><?php echo $term_obj->name; ?></td> <?php endforeach; ?> </tr> <?php endforeach; #$variations?> </tbody> </table> </div><!-- /table-responsive --> <?php endif; #$variations ?> This produces the following table: Product code System Pack Quantity Variation XT1ECWH 234 System 1 2 N/A XT2ECLWH 236 System 2 2 Left XT2ECRWH 237 System 2 2 Right XT3ECWH 238 System 3 2 N/AHowever, is it possible to alter the code to group the information? So it looks like the below? System 1 System 2 System 3 System 1XT1ECWH 234 Pack Quantity: 2 Variation: N/A System 2 XT2ECLWH 236 Pack Quantity: 2 Variation: Left XT2ECRWH 237 Pack Quantity: 2 Variation: Right System 3 Sorry, not sure why it's not formatted correctly but hopefully you can see what I'm trying to achieve. The array for $variations is as follows: Array ( [0] => Array ( [attributes] => Array ( [attribute_pa_system] => system-1 [attribute_pa_pack-quantity] => 2 [attribute_pa_variation] => n-a ) [sku] => XT1ECWH [variation_description] => [variation_id] => 234 ) [1] => Array ( [attributes] => Array ( [attribute_pa_system] => system-2 [attribute_pa_pack-quantity] => 2 [attribute_pa_variation] => left ) [sku] => XT2ECLWH [variation_description] => Left [variation_id] => 236 ) [2] => Array ( [attributes] => Array ( [attribute_pa_system] => system-2 [attribute_pa_pack-quantity] => 2 [attribute_pa_variation] => right ) [sku] => XT2ECRWH [variation_description] => Right [variation_id] => 237 ) [3] => Array ( [attributes] => Array ( [attribute_pa_system] => system-3 [attribute_pa_pack-quantity] => 2 [attribute_pa_variation] => n-a ) [price_html] => [sku] => XT3ECWH [variation_description] => ) ) If it helps, I need to always group by the first attribute, in this case : attribute_pa_system Any help on this would be very much appreciated! Thank you in advanced. Hey guys im having a issue with getting a radio group check box to work. Not sure what im doing wrong this is giving me a fatal error. Wanting to make it where only one box can be checked at a time. and when the attack from button is hit it assigns the value to $defender_planet <input type="checkbox" name="defender_planet" value="58"/> <input type="checkbox" name="defender_planet" value="59" /> <input type="checkbox" name="defender_planet" value="60" /> if(isset($_POST['attack_from'])) { $defender_planet = $this->input->post('defender_planet'); $planet3 = "SELECT defender_planet FROM travel WHERE defender_planet = '" .($defender_planet')."'"; $planet2 = mysql_query($planet3) or die(mysql_error()); $planet1 = mysql_fetch_array($planet2); $_SESSION['attacking_from'] = $planet1['defender_planet']; header("Location: attack.php"); exit(); } With unixtimestamps? I have let's say 20records, and like 5 of them are from January and 15 are in February, how would I go about showing all the records that were just in February (2012) or maybe 2013? (trick is using timestamps) Pretty much sort the records by each Monthy, by using unixtimestamp as the value in the db field, possible? i have a problem..my posts are showing up like this: July 6: post message July 6: post message July 6: post message im trying to get it like this: July 6: post message post message post message how do i group them like this in all in one post? |