PHP - Php Count - Instances Of A Certain Result - Game Scores
PHP/MYSQL - - - Thank you in advance for any help. Quick question. I am calc'ing whether each line db output is a win/loss/tie below. Outputting $res in each line. Is there a simple way to COUNT the number of instances where $ res = "win" or loss or tie?
I'd like to put an "overall" record at the top of the output. For example, for a given query, this chosen team's record is x WINS, Y Losses, Z TIES. Win/Loss/Tie is NOT a field in the db table. I know how to pull the total # of records pulled, but not this. Example User pulled a certain team to see game scores. 7 - 3 - 2 is their record. is what i'm trying to figure out Game Result Score Score opp Date game10 WIN * 7 2 blah game11 LOSS* 2 3 .... .... Code: [Select] //winloss begin works * above is a result of this code if ($row['sch_uba_score'] > $row['sch_opp_score']) $res = 'Win'; elseif ($row['sch_uba_score'] < $row['sch_opp_score']) $res = 'Loss'; else $res = 'Tie'; // winloss end works Similar TutorialsI'm trying to get a count of how many topics someone starts in a forum. I use XenForo, and they only count Posts, but I can order Posts by post_id and group those posts by thread_id to determine the initial instance of that topic. The problem I'm having is output. I'm getting the right User info, but the output is offset by one row: User 1 | 0 topics (because $c=0) User 2 | 128 topics (but those are User 1's #) User 3 | 0 topics (but those are User 2's #) User 4 | 141 topics (but those are User 3's #) etc
I realize as I play through the logic of the code, it's printing in that order. I can't seem to get the right order. I've tried various ways, with a couple of extra IF statements in there too.
$query = "select thread_id,user_id,username from ( select * from xf_post order by post_id ) x group by thread_id order by username,thread_id"; $results = mysqli_query($con,$query); echo mysqli_error($con); $c=0; $currentID = false; while($line = mysqli_fetch_assoc($results)) { if ($currentID != $line['user_id']) { echo '<div>' . $line['username'] . ', ' . $c; $currentID = $line['user_id']; $c=0; } else { $c++; } }
Hi I am building a product search engine using MySql and PHP (Jquery / AJAX). As i am getting the search results i wondered is it possible to count the instances of a category? For example: If i search for "Dell Laptops" i get 400+ results back because it has lots of laptops and accessories. What i am aiming for it to do is while looping through look at the categories and if its the first instanc eof it i want it to begin a count. until it has finished looping and then i can display it. Results: 436 [ Laptops(127) - Accesories (244) - Components(65) ] Im not even sure where to start here so any advice will be helpful Here is the code im using to generate the search: $id = str_replace(" ", "%", "$id"); $q = "SELECT * FROM products WHERE prod_name LIKE '%$id%' order by fee asc LIMIT 20"; 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 all, I'm struggling adding a count result to this script. I want each result to be an id so I can place x amountof images in one position and the remaining in another position. Each user might have different awards so just using the award_id is no good as there will be empty space so I need the actual result to display a id number. Code: [Select] $res = mysql_query("SELECT award, image FROM awards WHERE active = '1'"); $codes = array(); while ($row = mysql_fetch_assoc($res)){ $codes[$row['award']] = $row['image']; } $userid = '1'; $res = mysql_query("SELECT * FROM user_awards WHERE user_id = '$userid'"); $row = mysql_fetch_assoc($res); foreach ($codes as $award => $image){ if ($row[$award] == 1){ echo "<img src=../$image><br/>"; } } I echo number of mysql rows. But every second outputted number is position higher than normally. How to fix that? 4,5 are normal then 6 is like 5px higher, 7 is normal, 8 is higher, 9 is normal etc. Any ideas? $result = mysql_query("SELECT * FROM `friend_system` WHERE `friend_system_accepter` = '$myusername' "); echo mysql_num_rows($result);This displays the total rows in the table. $result = mysql_query("SELECT COUNT(friend_system_accepter) FROM `friend_system` WHERE `friend_system_accepter` = '$myusername' "); echo mysql_num_rows($result);This displays '1', which is incorrect. I want to echo out the number of rows where 'friend_system_accepter' = $myusername Thanks Hello, I am building an online game(users make a character and move on a map and so on...)
All user data is stored in a mySQL database and I want the users to interact in real-time, but there can be a 1-3 second delay between the communication, but not exceed 3 seconds even if 500 players are playing at the same time.
But for the purpose of the question let's say the users can only chat between one another, if I'll have a solution for that then I can use the same method for more parts of the game.
I can't use websockets because my webhost doesn't support it( I don't want to use pusher.com).
I know I can make real-time apps with ajax long polling, but I think that with 500 players playing at the same time it's not the best solution.
So, finally:
How can I make user interaction as close as possible to a real-time game?
(Without too much load on the hosting server)
(I am sorry if some of my terms are not correct - I am just getting back to coding after a long time...)
Edited by Mythion, 17 August 2014 - 02:34 AM. HOw to get the AVERAGE of my entire database? $query = "SELECT ROUND(AVG(scores)) FROM table"; Thanks! Bickey Hello, I have what I hope to be a very simple question.. I have built a game in flash and for my high score table I simply want to request the high scores in reverse.. i.e the lowest score first.. here is my php.. please help, thanks in advance !! :- <?php include("sqldialog.php"); $table = $_POST['tab']; $recept = SelectDatas($table, "name, score, dategame", "id > 0", "score desc"); if ($recept) { $i = 0; foreach ($recept as $rec) { $i++; if ($i==1) { $result .= "pseudo$i=".$rec['name']."&score$i=".$rec['score']."&dategame$i=".$rec['dategame']; } else { $result .= "&pseudo$i=".$rec['name']."&score$i=".$rec['score']."&dategame$i=".$rec['dategame']; } } echo $result; } else { echo "BAD, $pseudo, $score, $dategame,$ipclient"; } ?> This topic has been moved to Other. http://www.phpfreaks.com/forums/index.php?topic=357168.0 Hey, I've been working on a script to match playing card hands in a poker game against the river to return what the hand the user has and who won against other players. The problem is how do i approach an algorithm to do this in the first place. Cards are stored and structured by 2 characters seperated by a full stop. Example - 2 of diamonds and 3 of clubs is: D.2,C.3 now imagine a line of 5 cards (the river) and im trying to work out what they have and return the answer such as: 2 pairs or royal flush etc I so far decided my easiest way is to explode on the comma to get each card - then explode a second time on the full stop to get the suit and value into different variables. How ever - after that point im lost how i can do this up against the river to check what hand the user has. Any one got any tips on the best approach ? Hi all I have some code that displays the high scores for a game. Unfortunately, if a user has more than 1 high score in the table all scores for that user are displayed. I would like to only display the highest score per user. My Current Code Code: [Select] $sql_query = sprintf("SELECT * FROM `highscores` WHERE `gameID` = '106' ORDER BY `score` DESC"); //store the SQL query in the result variable $result = mysql_query($sql_query); if(mysql_num_rows($result)) { //output as long as there are still available fields while($row = mysql_fetch_row($result)) { echo ("$row[3] Scored :$row[5] <br>"); } } //if no fields exist else { echo "no values in the database"; } mysql_close($con); OutPut User1 300 User1 298 User 2 297 User1 296 User3 295 User2 290 I would like the output to be User1 300 User 2 297 User3 295 Any help is much appreciated Hi guys, I need your help. I am trying to insert the rows in the mysql database as I input the values in the url bar which it would be like this: Code: [Select] www.mysite.com/testupdate.php?user=tester&pass=test&user1=tester&email=me@shitmail.com&ip=myisp However i have got a error which i don't know how to fix it. Error: Column count doesn't match value count at row 1 <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbusername'); define('DB_PASSWORD', 'mydbpassword'); define('DB_DATABASE', 'mydbname'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $username = clean($_GET['user']); $password = clean($_GET['pass']); $adduser = clean($_GET['user1']); $email = clean($_GET['email']); $IP = clean($_GET['ip']); if($username == '') { $errmsg_arr[] = 'username is missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'PASSWORD is missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $sql = "INSERT INTO `members` (`username`,`email`,`IP`) VALUES ('$adduser','$email','$IP')"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } echo "The information have been updated."; } ?> Here's the name of the columns i have got in my database: Code: [Select] username IP I have input the correct columns names, so I can't correct the problem I am getting. Please can you help? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=331562.0 Why am I getting this error when there are 3 Fields with 3 values? Column count doesn't match value count at row 1 Code: [Select] $sql5="INSERT INTO participants (participant_name, team_no, sport) VALUES ('".implode("','$_POST[team]'),('",$_POST['participant_name'])."','$_POST[team]','$sport')"; I am using mod_php with Apache/2.4.6 (CentOS). I currently do not have multiple versions of PHP running on my server, but wish to do so now. Will I need to use php-fpm? Even if multiple instances can be accomplished with mod_php, is it typically preferred to use php-fpm? Any unusual gotcha's that I should be aware of? Will I need to uninstall mod_php before installing php-fpm? I previously used remi-php73 repo. Better to install from source? Thanks Edited August 25, 2019 by NotionCommotionI have a loop creating a block_vars array for displaying records from a database. (In this case auction listings). The following code creates this array: // get random selection of 6 items for home page display $query = "SELECT id, title, current_bid, pict_url, ends, num_bids, minimum_bid, bn_only, buy_now, subtitle, starts, ends, reserve_price FROM " . $DBPrefix . "auctions WHERE closed = 0 AND suspended = 0 AND starts <= " . $NOW . " ORDER BY RAND() DESC LIMIT 6"; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); $showendtime = false; $has_ended = false; $k = 0; while($row = mysql_fetch_assoc($res)) { $ends = $row['ends']; $difference = $ends - time(); if ($difference > 0) { $ends_string = FormatTimeLeft($difference); } else { $ends_string = $MSG['911']; } $high_bid = ($row['num_bids'] == 0) ? $row['minimum_bid'] : $row['current_bid']; $high_bid = ($row['bn_only'] == 'y') ? $row['buy_now'] : $high_bid; //determine whether the auction has a Buy Now price, show if appropriate. if($row['buy_now'] == '0.0000') { $bnamount = ""; } else { $bnamount = "<a href='" . $system->SETTINGS['siteurl'] . "buy_now.php?id=" . $row['id'] ."'>$" . substr($row['buy_now'], 0, -2) . "<br />" . "Buy Now</a>"; } //determine if the auction has a reserve set and if it has been met. display appropriate symbol if($row['reserve_price'] == '0.0000' && $row['bn_only'] == 'n' && ($row['current_bid'] < $row['minimum_bid'])) { $flag = '<img src="images/noreserve.gif" alt="No Reserve">'; $flagdesc = " No Reserve!"; $bnonly = "Current Bid<br />"; } else { if($row['current_bid'] >= $row['reserve_price']) { $flag = '<img src="images/reservemet.gif" alt="Reserve Met">'; $flagdesc = " Reserve Met!"; $bnonly = "Current Bid<br />"; } else { $flag = '<img src="images/noflag.gif">'; $flagdesc = ""; $bnonly = "Current Bid<br />"; } } if($row['reserve_price'] == '0.0000' && $row['bn_only'] == 'y') { $flag = '<img src="images/noflag.gif">'; $flagdesc = ""; $bnonly = "Asking Price "; $bnamount = ""; } $template->assign_block_vars('randomitems', array( 'ID' => $row['id'], 'BID' => $bnonly . "$" . substr($high_bid, 0, -2), 'IMAGE' => (!empty($row['pict_url'])) ? 'getthumb.php?w=' . $system->SETTINGS['thumb_show'] . '&fromfile=' . $uploaded_path . $row['id'] . '/' . $row['pict_url'] : 'images/email_alerts/default_item_img.jpg', 'TITLE' => $row['title'], 'BUY_NOW' => $bnamount, 'SUBTITLE' => $row['subtitle'], 'TIMELEFT' => $ends_string, 'NUMBIDS' => $row['num_bids'], 'FLAG' => $flag, 'FLAGDESC' => $flagdesc )); $k++; } Pretty straightforward. You will see I have a TIMELEFT value which will show on my home page as no.days, no.hours, no.mins until it closes etc. Here is the html in the tpl file: Code: [Select] <!-- BEGIN randomitems --> <div style="float:left;display:block;width:99%;border-bottom:#CCCCCC 1px solid;padding:2px;"> <div style="display:block;"> <table width="100%"> <tr> <td align="center" style="vertical-align:middle;width:120px" > <a href="{SITEURL}item.php?id={randomitems.ID}"><img src="{randomitems.IMAGE}" alt="{randomitems.TITLE}" style="border: none;width:120px"></a> </td> <td align="left" width="40%"> <table style="width:100%; vertical-align:middle; margin:0 auto"> <tr> <td><a id="itemdesc" href="{SITEURL}item.php?id={randomitems.ID}">{randomitems.TITLE}</a><br /> {randomitems.SUBTITLE}</td> </tr> <tr> <td id="closes">Closes in:{randomitems.TIMELEFT}</td> </tr> <tr> <td>{randomitems.FLAG}{randomitems.FLAGDESC}</td> </tr> </table> </td> <td id="buynow" align="center" width="15%"> {randomitems.BUY_NOW} </td> <td id="currentbid" align="center" width="25%"> {randomitems.BID} </td> </tr> </table> </div> </div> <!-- END randomitems --> This works quite nicely for me. What I want, and cannot manage thus far is to have the TIMELEFT value count down. The closest I have come is using a function like this: Code: [Select] <script type="text/javascript"> $(document).ready(function() { var currenttime = '{randomitems.TIMELEFT}'; function padlength(what) { var output=(what.toString().length == 1)? '0' + what : what; return output; } function displaytime() { currenttime -= 1; if (currenttime > 0){ var hours = Math.floor(currenttime / 3600); var mins = Math.floor((currenttime - (hours * 3600)) / 60); var secs = Math.floor(currenttime - (hours * 3600) - (mins * 60)); var timestring = padlength(hours) + ':' + padlength(mins) + ':' + padlength(secs); $("#ending_counter").html(timestring); setTimeout(displaytime, 1000); } else { $("#ending_counter").html('<span class="errfont">{L_911}</span>'); } } setTimeout(displaytime, 1000); }); </script> This code is placed in the tpl file and I simply give an html element the appropriate ID. The problem with this is that it would only show a countdown timer for the first item returned, which is no good as there are always six items returned. Can anyone offer a suggestion on how I could go about this? I can PM anyone with suggestions with a link to my development site so you know what I am raving about. I am really lost here with this date issue of mine. The below code is the last part of a query: Code: [Select] $defendercheck_3 = $row_checkifattacked3['atdate']; $defendercheck1_3 = strtotime("$defendercheck_3"); $defendercheck2_3 = date("D", $defendercheck1_3); The query does not return any results as expected, but when echoing the various steps I get following: echo "$defendercheck3"; = nothing (as expected) echo "$defendercheck1_3"; = nothing (as expected) echo "$defendercheck2_3"; = result! (NOT expected) why does it return anything on "date("D", $defendercheck1_3)" when "$defendercheck1_3" is blank? Anyone can help me? <?php $tbl_name="menu"; $kategorije = mysql_query("SELECT * FROM $tbl_name WHERE Left(menu_name, 1) BETWEEN 'A' AND 'M' ORDER BY menu_name ASC"); if (!$kategorije) { die("Database query failed: " . mysql_error()); } while ($row=mysql_fetch_array( $kategorije )) { echo "<div id=lista-header><h4>{$row["menu_name"]}</h4></div>"; $id_sub=$row['id_menu']; $podkategorije = mysql_query("SELECT * FROM submenu WHERE id_menu=$id_sub ORDER BY sub_name ASC", $connection); if (!$podkategorije) { die("Database query failed: " . mysql_error()); } echo "<ul class=\"pod\">"; while ($pod=mysql_fetch_array( $podkategorije )) { echo "<li><a href=index.php?=podkate?".$pod["id_sub"]." class=black>{$pod["sub_name"]}</a><hr size=1 align=left width=100px color=#cccccc></li>"; } echo "</ul>"; } ?> In this way, I get list with categories and hes subcategories. How to count how many subcategories have each categories, and count how many articles have each categories? Example (I wanna get this kind of look): Categories name (3) subcategoriesname (2) subcategoriesname (4) subcategoriesname (7) Categories name (5) subcategoriesname (1) subcategoriesname (14) subcategoriesname (9) subcategoriesname (2) subcategoriesname ( Categories name (2) subcategoriesname (28) subcategoriesname (17) Where the numbers represent how many categories and sub-items have articles |