PHP - Noob Question - Displaying Count By Group
Hi guys,
Sorry - I know this is a basic question but I've been out of the game for a year now and need to jog my memory. I am trying to count the number of rows per group. e.g: $sql = "SELECT *, COUNT(id) FROM image GROUP BY city"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); echo $row['COUNT(id)']; So if there are, for example, 5 New York's in the table, 3 London's and 2 Sydney's I want the echo to display 5, 3, 2 Should I use a loop for this? Cheers Similar TutorialsHi, 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 an array that looks like this:
array(5642) { [0]=> string(19) "2021-02-10 09:04:48" [1]=> string(19) "2021-02-10 09:04:54" [2]=> string(19) "2021-02-10 09:05:00" [3]=> string(19) "2021-02-10 09:05:06" [4]=> string(19) "2021-02-10 09:05:12" [5]=> string(19) "2021-02-10 09:05:18" [6]=> string(19) "2021-02-10 09:06:18" [7]=> string(19) "2021-02-10 09:06:24" }
I need to group the instances any time there is more than a 6 second gap between elements. So 0 =>5 would be one array and 6 and 7 would be a new array.
Ive been able to produce the following but its not ideal
array(5642) { [0]=> string(19) "2021-02-10 09:04:48" [1]=> string(19) "2021-02-10 09:04:54" [2]=> string(19) "2021-02-10 09:05:00" [3]=> string(19) "2021-02-10 09:05:06" [4]=> string(19) "2021-02-10 09:05:12" [5]=> string(19) "2021-02-10 09:05:18" [6]=> string(19) "end" [7]=> string(19) "2021-02-10 09:06:18" [8]=> string(19) "2021-02-10 09:06:24" }
$burner_time = array(); foreach($Burner_Control_Alm as $new_burner){ $burner_time[] = strtotime($new_burner); } $repl = 'end'; for ($i=1; $i<count($burner_time); $i++) { $value_second = $burner_time[$i]; $value_first = $burner_time[$i-1] === $repl ? $burner_time[$i-2] : $burner_time[$i-1]; if ($value_second > $value_first + 6) { array_splice($burner_time, $i++, 0, $repl); } print_r($burner_time); } hello, i have a table in a database that stores information on powerpoint presentations like so: id, title, filename, presenter, program, session I want to query the data so that all entries are grouped by session (which is a date) and each presentation is displayed under its respective session in a table like so: [session] (i want to display each session once) [title] - [program] (then i want to display this information for each presentation in each session) [presenter] [session] [title] - [program] [presenter] etc... i am thinking of using group_concat for this but am not sure exactly how to pull it off. any help is greatly appreciated. thank you! Hello, I have a social network that allows users to make comments and replies to comments. We have had a hacker attack us a couple of times in the passed couple of weeks via using our comment system manually, so I am trying to implement a limit on the amount of comments a user can make a day. this is what I have so far. The query before the insert query that counts based off the current date and than the query that inserts the comments. I'm just trying to figure out how to tie those together and determine what kind of if statement to do, and what to include in the if to make it work //QUERY TO FIND THE COUNT $query_count = "SELECT COUNT(*) FROM `CysticAirwaves` WHERE `FromUserID` = $auth->id AND date = `CURDATE()`"; $request = mysql_query($query_count,$connection); $result = mysql_fetch_array($request); //IF SHOULD GO HERE //INSERT THE COMMENT Code: [Select] $query = "INSERT INTO `CysticAirwaves` ( `FromUserID`, `ToUserID`, `comment`, `status`, `statusCommentAirwave`, `date`, `time` ) VALUES ( '" . $auth->id ."', '" . $prof->id ."', '" . mysql_real_escape_string($_POST['ProfileComment']) ."', 'active', 'active', '" . date("Y-m-d") . "', '" . date("G:i:s") . "')"; mysql_query($query,$connection); if($auth->id == $prof->id) { $just_inserted = mysql_insert_id(); $query = "UPDATE `CysticAirwaves` SET `status` = 'dead' WHERE `FromUserID` = '" . $auth->id . "' AND `ToUserID` = '" . $prof->id . "' AND `id` != '" . $just_inserted . "'"; $request = mysql_query($query,$connection); } Hi all i have a silly noob question.... When i directly query my database with the following i get the exact result i want....... Code: [Select] SELECT * FROM posts WHERE postTopic=3 AND postSubject=business; However when i try this using the following PHP....... $sql = "SELECT * FROM posts WHERE postTopic =" . mysql_real_escape_string($_GET['id']) . "AND postSubject='" . $_SESSION[forum] . "'"; I get no result I also get the correct results from $sql = "SELECT * FROM posts WHERE postTopic =" . mysql_real_escape_string($_GET['id']) . "; and $sql = "SELECT * FROM posts WHERE postSubject='" . $_SESSION[forum] . "'"; mysql_real_escape_string($_GET['id']) is an integer and $_SESSION[forum] is a string. I know this has something to do with the manner in which the query is passed with the AND and the string but i can't for the life of my work out where i am going wrong. Thanks for any help. OK, so I have a question about databases and how they sort things being loaded into them. I have a database that I have images uploaded to (some people dont like to do it this way but this is what is going to work for my project). I have it set up with an id column that auto-increments. When I upload the files for some reason it is putting the highest id number first and the second one is the lowest then it goes in order from there. Why would this be happening and how do I correct it? Long story short i'm paginating database results. So pages = results / res-per-page-limit but 28 / 10 will be 2.8 should i use round() or ceil()? I'm really sorry if this has been answered (I assume it has) I'm unfamiliar with search terms of what I am trying to do. I have this web page Code: [Select] <html> <body> <?php $con = mysql_connect("localhost","user","pass"); if (!$con) { echo "Fail"; die('Could not connect: ' . mysql_error()); } echo "Triumph"; ?> </body> </html> Which I got from a snippet. I load the webpage expecting to see fail or triumph, but I see nothing. My question is how to run the php script so I see something on the page (hopefully triumph. I apoligise for my noobness, I'm a PHP know nothing at the moment. OK so sorry if my understandings a bit off, but if a I want to introduce a class into my doc is the best way to fo this with the include() function? But how do I check input to make sure that the input has to be seperated by commas and has to be a integer like "1,2,3,4,5" is correct if a user puts "1,:25,,l2@" or something funky, I can error out Thanks also is there a php function that does this already? and is this way safe? im trying to store comma seperated id's I hope no one rolls their eyes at me, lol, but I literally, just made my first PHP script, but I ran into a snag.
Okay so the code I did was
<!DOCTYPE html> <html> <body> <?php echo <h1>"my First PHP script"</h1>; ?> </body> </html> but in firefox the outcome is always "my first PHP script?> I had added the h1 tags because it wouldn't print at all before I did. I'm trying to figure out what I did wrong. So I'm using simplexml_load_file($url) to load up a client's XML file so I can use it with a jQuery slide show right. My problem is that some of the strings within the xml files are often times sentences and when I echo, for example... Code: [Select] echo $xml->images->categories->category[$gallery]->images->image[0]->description[0]; I should see Dream as if you'll live forever, Live as if you'll die today but all I'm getting is Dream as if you It appears as though php is getting confused when it sees those little single quotes. Anyone? hey guys! I just got started with php (yesterday) and im currently trying to write a script that cuts email signatures off. The first filter ($sig[0]) works fine, the string is cut and posted- and, well, that's it. I think i did sth wrong within the for- but i cant find it. So please help me out. A hint would be fine already. Thanks in advance- and here is some code: Code: [Select] <?php $string="TESTSTRING!! I AM AN EMAIL TEXT!!! SO RANDOM! --- I AM A SIGNATURE!! HERP DERP CUT ME OFF"; //define possible sig starts (=filter) $sig[0]=("#=="); $sig[1]=("---"); $sig[2]=("the name of an enterprise"); $sig[3]=("___"); for ($i=0; $i<=3; $i++) { /* or count($sig) ? */ $sigpos=strpos($string,$sig[$i]); if($sigpos>0) { $string= substr($string,0,$sigpos); break; echo $string; } else { echo $string; break; } } ?> <br> <? //show where the sig is cut off echo $sigpos; ?> Hi everyone Well I've started learning php yesterday and now I encountered my first problem, I looked around but I don't really know what to search for if I want my answer so here I come Code: [Select] <html> <body> <?php $names = array('Peter','Quagmire','Joe'); $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); $who = rand(0,2); $who2 = $names[$who]; echo "$names[$who] is $ages[$who2] years old"; ?> </body> </html> This is the script I have, and there is the kind of script I expected: Code: [Select] <html> <body> <?php $names = array('Peter','Quagmire','Joe'); $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); $who = rand('Peter','Quagmire','Joe'); echo "$who is $ages[$who] years old"; ?> </body> </html> But after some search I concluded that rand is only used for random numbers So, my question is, which function should I use to achieve my goal? Is there any randstring('string1','string2',etc) command? Tnx for your time Hello everyone! I'm completely new to PHP and Databases. I've managed to do some nice work by reading, but now I've encountered a problem I can't solve. I made a site with trailers and got tierd of adding them manually. So I created a form which sends the trailer info to my database. There's now trailers in specific organized genres. But the list is beginning to get really big so I wanted to show just 10 trailers per page. And so I found out I could use a paging system which I ALMOST got working. Just one last thing that needs to be fixed and that is when I click on next page "http://www.xxxxxxxx.com/test.php&page=2" it doesn't show the content. While "http://www.xxxxxxxx.com/test.php" does. So I just need that next button to work, I don't know if theres something missing or what it is... Note: I'm new to all this so please excuse my very very bad coding. Here is my code: test.php <link rel="stylesheet" type="text/css" media="all" href="http://www.xxxxxxxxxxxxx.n.nu/createdfiles/trailers/style-twentyten.css" /> <link rel="stylesheet" type="text/css" media="all" href="http://www.xxxxxxxxxxxxx.com/paginate.css" /> <?php $rpp = 10; // results per page $adjacents = 4; $page = intval($_GET["page"]); if(!$page) $page = 1; $reload = $_SERVER['PHP_SELF']; // connect to your DB: $link_id = mysql_connect("server","username","my password"); mysql_select_db("database"); // select appropriate results from DB: $sql = "SELECT * FROM blablabla WHERE Genre LIKE '%Drama%' ORDER BY `blablabla`.`sort` DESC LIMIT 0, 9999"; $result = mysql_query($sql, $link_id); // count total number of appropriate listings: $tcount = mysql_num_rows($result); // count number of pages: $tpages = ($tcount) ? ceil($tcount/$rpp) : 1; // total pages, last page number $count = 0; $i = ($page-1)*$rpp; while(($count<$rpp) && ($i<$tcount)) { mysql_data_seek($result,$i); $query = mysql_fetch_array($result); // output each row: echo "<br />--------------------------------------------------------------------------------------------------------<br /><br />"; ?><strong> <img src=" <?php echo $query['Poster'];?>" /><?php echo "<br /> <br />"; ////////////////////////////// //SHOW TITLE, YEAR AND GENRE// ////////////////////////////// echo "<H1>"; echo $query['Title']; echo "<br /> <br />"; echo "</h1>"; ?></strong> <?php echo "<H2>"; echo $query['Year']; echo "</H2>"; echo "<br />"; echo "<H3>"; echo $query['Genre']; echo "</H3>"; ?> <a href=" <?php ////////////////////////////// //SHOW IMDB, ACTORS AND PLOT// ////////////////////////////// echo $query['IMDB']; ?> " target="_self">Link to IMDb</a> <?php echo "<br /> <br />"; echo "<H2>Stars:</H2>"; echo "<br />"; echo "<H3>"; echo $query['Actors']; echo "</H3>"; echo "<br />"; echo "<H2>Plot:</H2>"; echo "<br />"; echo "<H3>"; echo $query['Plot']; echo "</H3>"; echo "<br /> <br />"; echo "<H2>"; //////////////// //SHOW TRAILER// //////////////// ?> <div id="<?php echo $query['ID'];?>" style="display: none;"> <?php echo $query['Youtube']; echo "</div>"; ?> <a href="javascript:ReverseDisplay('<?php echo $query['ID'];?>')">Click to show/hide trailer.</a> <?php echo "</H2>"; echo "<br /> <br />"; $i++; $count++; } // call pagination function: include("paginate_one.php"); echo paginate_one($reload, $page, $tpages); ?> <?php //////////////////////////////// //SCRIPT FOR SHOW/HIDE TRAILER// //////////////////////////////// ?> <script type="text/javascript" language="JavaScript"><!-- function HideContent(d) { document.getElementById(d).style.display = "none"; } function ShowContent(d) { document.getElementById(d).style.display = "block"; } function ReverseDisplay(d) { if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; } else { document.getElementById(d).style.display = "none"; } } //--></script> paginate_one.php <?php /************************************************************************* php easy :: pagination scripts set - Version One ========================================================================== Author: php easy code, www.phpeasycode.com Web Site: http://www.phpeasycode.com Contact: webmaster@phpeasycode.com *************************************************************************/ function paginate_one($reload, $page, $tpages) { $firstlabel = "First"; $prevlabel = "Prev"; $nextlabel = "Next"; $lastlabel = "Last"; $out = "<div class=\"pagin\">\n"; // first if($page>1) { $out.= "<a href=\"" . $reload . "\">" . $firstlabel . "</a>\n"; } else { $out.= "<span>" . $firstlabel . "</span>\n"; } // previous if($page==1) { $out.= "<span>" . $prevlabel . "</span>\n"; } elseif($page==2) { $out.= "<a href=\"" . $reload . "\">" . $prevlabel . "</a>\n"; } else { $out.= "<a href=\"" . $reload . "&page=" . ($page-1) . "\">" . $prevlabel . "</a>\n"; } // current $out.= "<span class=\"current\">Page " . $page . " of " . $tpages . "</span>\n"; // next if($page<$tpages) { $out.= "<a href=\"" . $reload . "&page=" .($page+1) . "\">" . $nextlabel . "</a>\n"; } else { $out.= "<span>" . $nextlabel . "</span>\n"; } // last if($page<$tpages) { $out.= "<a href=\"" . $reload . "&page=" . $tpages . "\">" . $lastlabel . "</a>\n"; } else { $out.= "<span>" . $lastlabel . "</span>\n"; } $out.= "</div>"; return $out; } ?> Here you can view a test of it all in action: http://www.mansgullberg.com/test.php please dont hack my site I'm thankfull for all of your answers! Really nice forum this! /kvickan I'm almost embarrassed to ask such a simple question but I just cannot get this to work. I'm trying to figure out how to use sessions that takes the information from a form on the first page and displays it on the last. I have this on page 1: <?php session_start(); ?> <form action="test2.php" method="post"> <p>Page 1</p> <p>First Name <input type="text" name="first" /></p> <p><input type="submit" value="Next page 2" /></p> And this for page 2: <?php SESSION_START(); $_SESSION['first'] = $_POST['first']; echo $_SESSION['first'] = $_POST['first']; ?> <form action="test3.php" method="post"> <p>Page 2</p> <input type="submit" value="Next page 3" /> </form> And this for page 3: <?php SESSION_START(); $_SESSION['first'] = $_POST['first']; echo $_SESSION['first'] = $_POST['first']; ?> <p>Page 3</p> <p>You're done</p> I can get it to display on page 2 but not on page 3. Can anyone tell me why? I've been at this for a long time and it should be simple but I cannot get it to work. Thanks in advance. Hello there. I used this code so many times long ago, but I still don't remeber and don't know what I'm doing wrong. http://circus.ka-blooey.net/ If I try to click on any link below the post, I got the error: Code: [Select] Warning: include(.php) [function.include]: failed to open stream: No such file or directory in /home/kablooey/public_html/circus/index.php on line 5 Warning: include(.php) [function.include]: failed to open stream: No such file or directory in /home/kablooey/public_html/circus/index.php on line 5 Warning: include() [function.include]: Failed opening '.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/kablooey/public_html/circus/index.php on line 5 -----------------------x My index is: Code: [Select] <?php include("header.php"); ?> <? if (empty($_GET["boo"])) {$boo="news/show_news";} include "$boo.php"; ?> <?php include("footer.php"); ?> and the footer, where the links are is: Code: [Select] <br /> <div id="menu"><center><a href="http://circus.ka-blooey.net">clear</a> ---x--- <a href="?boo=out">links out</a> ---x--- <a href="?boo=credits">credits</a></center></div><br /> <br /> <br /> <div id="footer"><img src="http://circus.ka-blooey.net/layout/circus_footer.jpg" /></div> </div> </div> </div> </body> </html> Help please? =/ I need to add a condition to a while() statement I have. It should run when $counter is less than the number of records in my $products array which has 5 products. I set $counter and $product_no to 0. I need to use the count() function to get the number of records. Does that make sense? Do ya'll need more info. Any help is Greatly appreciated. Ive referenced and searched but cant figure out how to incorporate it. Im still learning. Peace, Skrappy Hi All, The following code works but for some reason it is leaving 1 result off of each page when displaying results from DB. I assume there is something wrong with the count but I cannot find the problem. Thank you for any help. Code: [Select] <?php $page = $_GET['page']; $result2 = mysql_query("SELECT * FROM vendors WHERE vendor_type_id = '$vdrt' AND active ='Yes' ORDER BY RAND()"); $total_results = mysql_num_rows($result2); if (empty($total_results)) {echo "Sorry, but we do not have any results for that search at this time. <br/><br/><a href='index.php'>Please try your search again</a>";} else { $total_pages = ceil($total_results / $results_limit); // $results_limit is set to 7 in config file if (empty($page)) { $page = "1"; } $offset = ($page - 1) * $results_limit; $result = mysql_query("SELECT * FROM vendors WHERE vendor_type_id = '$vdrt' AND active ='Yes' LIMIT $offset, $results_limit") or die ("$DatabaseError"); $row = mysql_fetch_assoc($result); $vendor_type_id = $row['vendor_type_id']; $num = mysql_numrows($result); if ($num == 0) : print "<br><br><p>Sorry, no vendors could be found.</p><br><br>"; elseif ($num > 0) : echo "Page - "; if ($page != 1) { echo "<a href=$PHP_SELF?city=Orlando&state=FL&vdrt=$vendor_type_id&page=1><< First</a> "; $prevpage = $page - 1; } if ($page == $total_pages) { $to = $total_pages; } elseif ($page == $total_pages-1) { $to = $page+1; } elseif ($page == $total_pages-2) { $to = $page+2; } else { $to = $page+3; } if ($page == 1 || $page == 2 || $page == 3) { $from = 1; } else { $from = $page-3; } for ($i = $from; $i <= $to; $i++) { if ($i == $total_results) $to=$total_results; if ($i != $page) { echo "<a href=$PHP_SELF?city=Orlando&state=FL&vdrt=$vendor_type_id&showold=yes&page=$i>$i</a>"; } else { echo "<b><span class='current-page'>[$i]</span></b>"; } if ($i != $total_pages) echo " "; } if ($page != $total_pages) { $nextpage = $page + 1; echo " <a href=$PHP_SELF?city=Orlando&state=FL&vdrt=$vendor_type_id&page=$total_pages>Last >></a>"; } if ($num == 0) { echo "<br><br>";} else {echo "<br><br>";} $i = 0; while ($i < $num) : while ($row = mysql_fetch_assoc($result)) { $vdrid = $row['vendor_id']; $vendor_name = $row['vendor_name']; $vendor_name_enc = urlencode($row['vendor_name']); $vendor_city = $row['vendor_city']; $vendor_state = $row['vendor_state']; $vendor_phone = $row['vendor_phone']; $vendor_overview = $row['vendor_overview']; // Trim overview if(strlen($vendor_overview) > 385) {$trimed_vendor_overview = substr($vendor_overview,0,385) . "..."; } else { $trimed_vendor_overview = $vendor_overview; } echo "<strong><a href='listing.php?$vendor_name_enc-$vendor_city-$vendor_state-&vdrid=$vdrid'>$vendor_name</a> </strong> - $vendor_city, $vendor_state $vendor_phone<br/>"; echo "$trimed_vendor_overview<br/><br/>"; } $i++; endwhile; endif; } ?> hey guys! Im trying to get hashtags out of a string. The function works so far- but i cant transfer the insides of the preg_match_all array into the string. A hint would be fine already. Thanks in advance- and here is some code Code: [Select] <?php //example string $strcontent = "ima string... #wat #taggy #taggytag im in your stringz, stealing your charz!"; //find hashtags preg_match_all("/(#\w+)/", $strcontent, $matches); echo $matches; //the output is just "array" -> why? foreach ($matches as $match) { // $tempmatch=$match[1]; #####like this? //hiding the hashtags via span $strtemp="<br>ima span<br>" . $match . "<br>ima /span<br>" . $strcontent; $strcontent = $strtemp; echo $strcontent; } #echo $strcontent; # <span style="display:none;"></span> ?> |