PHP - Csv Group Duplication
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 Similar TutorialsAs part of an image gallery I am trying to INSERT data into a table to make accessible the relevant info of individual images - the problem I have encountered is that each query seems to be being inserted twice, and I can't figure out why. The code = Code: [Select] <?php /*============================================== Connect to MySQL and select the correct database ==============================================*/ mysql_connect("localhost", "uname", "pwd") or die(mysql_error()); echo "Connected to MySQL<br />"; mysql_select_db("gallery_db") or die(mysql_error()); echo "Connected to Database gallery_db.<br />"; /*============================================= Include the files needed to undertake this task =============================================*/ include("functions.php"); /*========================= Set up arrays and variables =========================*/ $store = array(); $exif = array(); $folder = "./images/"; $insrt = 'INSERT INTO images VALUES (img_id, '; $file_name = ''; $file_location =''; $copyright =''; $caption = ''; $file_date = ''; $file_time = ''; $camera = ''; $speed = ''; $fNo = ''; $ISO = ''; /*================================= Open folder and read relevant files =================================*/ if ($handle = opendir('./images')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $file_name = $file; //>>> File Name <<< $file_location = $folder . $file; //>>> File Location <<< $exif = exif_read_data($file_location, 'EXIF'); //>>> Read exif data <<< /*============================================================== Check if the 'Copyright' info existe in the exif data, and if it doesn't set the $copyright variable to the relevant value. ==============================================================*/ if (array_key_exists('Copyright', $exif)) { $copyright = $exif['Copyright']; } else { $copyright = "copy name"; } $caption = $exif['COMMENT'][0]; //>>> Get the Caption <<< //>>> Re-format DateTime into separate date and time var's $file_date & $file_time <<< $temp = substr($exif['DateTime'], 0, 10); $file_date = substr($temp, 8, 2) . substr($temp, 4, 4) . substr($temp, 0, 4); $file_time = substr($exif['DateTime'], 11, 8); //>>> Set the rest of the variables <<< $camera = $exif['Model']; //>>> Get the camera make and model <<< $speed = $exif['ExposureTime']; //>>> Get the shutter speed <<< $fNo = $exif['COMPUTED']['ApertureFNumber']; //>>> Get the f No. <<< $ISO = $exif['ISOSpeedRatings']; //>>> Get the ISO rating <<< //>>> Fill the $store[] array with the relevant bits for each seperate query <<< $store[] = $insrt . "'" . $file_name . "', " . "'" . $file_location . "', " . "'" . $copyright . "', " . "'" . $caption . "', " . "'" . $file_date . "', " . "'" . $file_time . "', " . "'" . $camera . "', " . "'" . $speed . "', " . "'" . $fNo . "', " . "'" . $ISO . "')"; } } closedir($handle); } /*============================================================================= Get individual queries from $store[] and INSERT INTO images the relevant VALUES =============================================================================*/ $num_queries = count($store); //>>> Check the number of queries in the array $store $loop = 0; //>>> Starting point for query No. bearing in mind that array keys are numbered from zero while ($loop <= $num_queries - 1) { $query = $store[$loop]; if (!mysql_query($query)){ die('Error: ' . mysql_error()); } mysql_query($query); $loop++; } ?> I know it's not pretty, but that can be attended to once working properly. I am quite sure that it will be a very simple solution, probably so simple that I haven't even thought of it. I've recently had a problem with my admin site where PHP sessions, which are stored in a MySQL database, are duplicating and causing the page to return to the login screen. Usually the site works fine in Firefox, but stops working in IE and Safari. This problem suddenly appeared over night with no change to the files. Due to the amount of code, I'm reluctant to post it all, but does anyone have a suggestion on why this could be happening and how to solve it? Hello there, I'm looking for a PHP method to duplicate a line, for example if I wanted to duplicate this line: mail($to,$subject,$message,$headers); How could I specify a value of how many are displayed instead of doing this to send it 3 times: mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); Many thanks Hi everyone, I don't know whether this is a PHP or MySql problem, but I think it is the former. The following code queries the database correctly, (and before you ask, there are no duplicate database entries), but the output duplicates every row. e.g., hammer (jpg image) hammer hammer (jpg image) hammer saw (jpg image) saw saw (jpg image) saw screwdriver (jpg image) screwdriver screwdriver (jpg image) screwdriver and so on. I cannot see why the code causes the row to repeat. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { // Put stored session variables into local php variable $id = $_SESSION['id']; $userId = $_SESSION['userId']; $userGroup = $_SESSION['userGroup']; $managerId = $_SESSION['managerId']; } include_once("demo_conn.php"); $sql = mysql_query("SELECT * FROM users WHERE id='$id'"); while($row = mysql_fetch_array($sql)) { // Get member data into a session variable $egroup = $row["egroup"]; session_register('egroup'); $_SESSION['egroup'] = $egroup; } $query = mysql_query("SELECT topics.url_big, topics.url_small, topics.title, topics.$egroup, quiz.passState, quiz.userDate FROM topics INNER JOIN quiz ON (topics.managerId = quiz.managerId) WHERE topics.$egroup = 1 ORDER BY title ASC"); while ($row1 = mysql_fetch_array($query)) { echo "<a href='../../wood/wood_tool_images/{$row1['url_big']}' target='_blank'><img src='../../wood/wood_tool_images/{$row1['url_small']}' /><br />\n"; echo "{$row1['title']} <br />\n"; } ?> <?php // Daniel URL duplicator. // Input links list. $linksList = "links.txt"; // How many times to duplicate the url? $manyTimes = 1000; // Read in the list. for ($x = 0; $x <= $manyTimes; $x++) { $handle = fopen($linksList, "r"); $line = fgets($handle); echo $line; fclose($handle); } ?>Hey Guys, I'm stuck on this simple bit of code lol what I'm trying to do is load in a list of urls: site1.com site2.com site3.com etc For each site that is read, I'm trying to duplicate it X times, above would print to screen the same url 1000 times, then move onto the next print it 1000 times etc until the list is done (or how ever many times I select) I can't think of the best way to do it! any help would be appreciated guys! Graham Hi I have this simple code $one = rand(1,9); $two = rand(1,9); $three = rand(1,9); but I need to change it so that they are all unique and the same number is not used more than once can anyone help? thanks Please help and amend the code Save without repetition required $read[0] I hope that my example is clear to you I apologize for bothering you. I am not good in English <?php $fileLocation = getenv("DOCUMENT_ROOT") . "/rt.txt"; $file = fopen($fileLocation,"a"); $n1 = $_POST['n1']; $n2 = $_POST['n2']; for($i = 0; $i < count($file); $i++){ $read = explode("|", $file[$i]); if($n1 == $read[0]){ echo 'Repetition'; } else { fwrite($file,$n1.'|'.$n2."\r\n"); }
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 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.
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, 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 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=353968.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! This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306114.0 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? 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. 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. 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 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 |