PHP - Generate Names, Random Ordered Games And Cron Jobs! (3 Questions)
Basically I am setting up my own cricket management game, but there are 3 areas that I am slightly stuck on and would appreciate help:
1) When a use registers, I need to create 11 players for their team. For this, I am going to have one text files with first names and one text file with surnames. How can I open each file and select a name and then match them together? 2) I need to create the list of games to be executed at particular times through a cron job. How can I go through all the teams in a table and match them together in games, ensuring everyone plays everyone? If a new player registers, he will be put into a random league and so the games for that league will have to be redone 3) How can I set up a cron job to execute the above games? Each team should play once a day and so if there are 24 teams in a table, there will be 12 games that occur through this cron job. I assume cron jobs are the best thing for this. Any help would be appreciated. Thanks. Similar TutorialsPHP + MySQL This has been doing my head in, it has to be possible how I think it is. The thing I am trying to achieve here is let's say a list of users logged in. Now if every one would click logout and use the system correctly the world would be a better place, but they wont, we all know this. So I was thinking how to counter this and I came up with an idea, lets say in our users table we have an "ACTION" field as a timestamp (or datestamp??). So everytime the user does anything on my site, edit there profile, browse something etc etc, it updates the "ACTION" field to the current time. I was thinking in the background I could have a cron job run every.. 5 minutes? Is it possible to have it check EVERY users ACTION field and if there ACTION field is less than the current time - 5 minutes, it updates there LOGGED_IN field to like 0, which would mean they're actually not logged in anymore and would not appear in the logged in list. Someone tell me yes or no! (The main problem being having to constantly update that ACTION field) hello im having trouble with this code im not sure if you can help me but ima paste the code here and i will see what people say, the problem is this: PHP Fatal error: require(): Failed opening required '../class/class_db_mysql.php' (include_path='.:') in /var/www/vhosts/dclxvi.co.uk/httpdocs/crons/cron_day.php on line 6 my code is this: <?php include_once ('../Global/config.php'); global $_CONFIG; if($_GET['code'] != $_CONFIG['code']) { die(""); } define("MONO_ON", 1); require "../class/class_db_{$_CONFIG['driver']}.php"; $db=new database; $db->configure($_CONFIG['hostname'], $_CONFIG['username'], $_CONFIG['password'], $_CONFIG['database'], $_CONFIG['persistent']); $db->connect(); $c=$db->connection_id; $db->query("UPDATE fedjail set fed_days=fed_days-1"); $q=$db->query("SELECT * FROM fedjail WHERE fed_days=0"); $ids=array(); while($r=$db->fetch_row($q)) { $ids[]=$r['fed_userid']; } if(count($ids) > 0) { $db->query("UPDATE users SET fedjail=0 WHERE userid IN(".implode(",", $ids).")"); } $db->query("DELETE FROM fedjail WHERE fed_days=0"); $db->query("UPDATE users SET daysingang=daysingang+1 WHERE gang > 0"); $db->query("UPDATE users SET daysold=daysold+1, boxes_opened=0"); $db->query("UPDATE users SET mailban=mailban-1 WHERE mailban > 0"); $db->query("UPDATE users SET donatordays=donatordays-1 WHERE donatordays > 0"); $db->query("UPDATE users SET cdays=cdays-1 WHERE course > 0"); $db->query("UPDATE users SET bankmoney=bankmoney+(bankmoney/50) where bankmoney>0"); $db->query("UPDATE users SET cybermoney=cybermoney+(cybermoney/100*7) where cybermoney>0"); $q=$db->query("SELECT * FROM users WHERE cdays=0 AND course > 0"); while($r=$db->fetch_row($q)) { $cd=$db->query("SELECT * FROM courses WHERE crID={$r['course']}"); $coud=$db->fetch_row($cd); $userid=$r['userid']; $db->query("INSERT INTO coursesdone VALUES({$r['userid']},{$r['course']})"); $upd=""; $ev=""; if($coud['crSTR'] > 0) { $upd.=",us.strength=us.strength+{$coud['crSTR']}"; $ev.=", {$coud['crSTR']} strength"; } if($coud['crGUARD'] > 0) { $upd.=",us.guard=us.guard+{$coud['crGUARD']}"; $ev.=", {$coud['crGUARD']} guard"; } if($coud['crLABOUR'] > 0) { $upd.=",us.labour=us.labour+{$coud['crLABOUR']}"; $ev.=", {$coud['crLABOUR']} labour"; } if($coud['crAGIL'] > 0) { $upd.=",us.agility=us.agility+{$coud['crAGIL']}"; $ev.=", {$coud['crAGIL']} agility"; } if($coud['crIQ'] > 0) { $upd.=",us.IQ=us.IQ+{$coud['crIQ']}"; $ev.=", {$coud['crIQ']} IQ"; } $ev=substr($ev,1); if ($upd) { $db->query("UPDATE users u LEFT JOIN userstats us ON u.userid=us.userid SET us.userid=us.userid $upd WHERE u.userid=$userid"); } $db->query("INSERT INTO events VALUES('',$userid,unix_timestamp(),0,'Congratulations, you completed the {$coud['crNAME']} and gained $ev!')"); } $db->query("UPDATE users SET course=0 WHERE cdays=0"); $db->query("TRUNCATE TABLE `votes`"); ?> Hello there.. my webhost doesn't have Cron Jobs feature.. is there any alternative php script in able to run my php script every minute ?? i have a website containing mafia game.. it's coded in php.. i tried to use Code: [Select] <META HTTP-EQUIV="Refresh" CONTENT="60; URL=http://test.com/run_minute.php">but this will work only if the user is in the existing page where this code placed.. i want it something like, the http://test.com/run_minute.php will refresh every minute.. even thou the user is not on the page.. Thank you. More power.. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=333230.0 This topic has been moved to Linux. http://www.phpfreaks.com/forums/index.php?topic=306518.0 Hi there. I need a function that can generate 15 random numbers between (1,10) and then converts those numbers to Roman numbers. Anyone can help me? Hi, im trying to apply a random css class to a div so that a random image is generated on each refresh. This is the code i am using to apply the class. Code: [Select] <div class="<?php echo($randomimage); ?>"> Say i have an array of $image1 $image2 $image3 etc, how can i make $randomimage = 1 of these at random on each refresh? I've found lots of tutorials that generate a random number online but none that generate a random variable and am having trouble piecing this together. Any help would be hugely appreciated. Richard So I found this code from someone else on here who posted about creating a random string. I've copied the code for myself but when I upload php page to my server and view source... there is no php code. Essentially, i see no randomly generated text. what am i missing? Code: [Select] <?php function genRandomString() { $length = 5; $characters = array_merge(range(0,9),range('a','z'),range('A','Z')); $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, count($characters)-1)]; } return $string; } ?> Hi, I have a script to add images to my tabel and and upload them to my server, I have managed to get the upload script to rename the image with a 5 digit random number on the end to prevent overwriting, the only problem I can't seem to be able to add the same name to my tabel. Any ideas? Thanks in advance. Code: [Select] <?php $idir = "uploads/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], $idir. basename($_FILES['fupload']['name'], $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Perm } } if (isset ($_FILES['fupload2'])){ //upload the image to tmp directory $url = $_FILES['fupload2']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload2']['type'] == "image/jpg" || $_FILES['fupload2']['type'] == "image/jpeg" || $_FILES['fupload2']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload2']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload2']['tmp_name'], "$idir" . $_FILES['fupload2']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload3'])){ //upload the image to tmp directory $url = $_FILES['fupload3']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload3']['type'] == "image/jpg" || $_FILES['fupload3']['type'] == "image/jpeg" || $_FILES['fupload3']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload3']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload3']['tmp_name'], "$idir" . $_FILES['fupload3']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload4'])){ //upload the image to tmp directory $url = $_FILES['fupload4']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload4']['type'] == "image/jpg" || $_FILES['fupload4']['type'] == "image/jpeg" || $_FILES['fupload4']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload4']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload4']['tmp_name'], "$idir" . $_FILES['fupload4']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } $usr = "user"; $pwd = "pass"; $db = "db"; $host = "host"; # connect to database $cid = mysql_connect($host,$usr,$pwd); if (!$cid) { echo("ERROR: " . mysql_error() . "\n"); } if ($_POST['submit']) { $logo = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $image1 = mysql_real_escape_string("$idir" . $_FILES['fupload2']['name']); $image2 = mysql_real_escape_string("$idir" . $_FILES['fupload3']['name']); $image3 = mysql_real_escape_string("$idir" . $_FILES['fupload4']['name']); $SQL = " INSERT INTO mhhire "; $SQL .= " image1, image2, image3, logo) VALUES "; $SQL .= " ('$image1', '$image2', '$image3', '$logo') "; $result = mysql_db_query($db,$SQL,$cid); $last=mysql_insert_id(); if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } header("location:thanks.php"); exit(); } ?> How do you generate a random number like say, 0 through 10? I want to select random sites from my database that have IDs 0 through 10. Hi All, I created this simple function to generate random doubles..... Please your opinions! function GetRandomFloatNumber($min = false, $max = false, $dec_min = false, $dec_max = false) { // Seed the generator mt_srand((double)microtime()*1000000); // Set the default min and max if no parameter has been passed if ($min === false) $min = 0; if ($max === false) $max = mt_getrandmax(); if ($dec_min === false) $dec_min = 0; if ($dec_max === false) $dec_max = mt_getrandmax(); // units $units = mt_rand($min, $max); // Decimals $decimals = mt_rand($dec_min, $dec_max); // Set double $doublenumber = $units.'.'.$decimals; // Return double return $doublenumber; } How to generate a unique random number in php??? Any one who can help me? Hello........ Currently i am struggling with php script....... can any one tell me or guide me how to code Automatically generating random number with in the range of 19 to 90 and the number has to change with in 24 hours time duration......... It's urgent........ Thanks in advance..... Rooban.S I am looking to generate a random number for every user contribution as a title of the contribution. I could simply check the database each time with a query and generate a number which does not equal to any of the entries of the database. But I imagine this as inefficient and it could become slow if the database is big in my opinion. Also I'd have to contain all the numbers of the database somewhere to manage the "not equals to", in an array or something similar but that can end up as a giant one. Excuse the layman's speech I am new to this. Any suggestions how this can be solved efficiently without straining the resources too much? You can explain it linguistically and do not have to provide me any scripts, I will figure it out. This might be a bit hard to explain! I have a grid, 32x32 which is actually 1024 mySQL rows in a table, you can see the table he http://interbitlotto.com/grid each cell is a row in the database, top left is ID 1, bottom right is id 1024. get it? right well its a battle ship game, and im stuck on the automatic battle ship placement script. I have displayed the generated boats as misses so we can see them. The problem i am having, is that the random number generater chooses a cell too close to the side so the boat ends up wrapping to the other side. I cant think of a way to detect if its going to wrap, if it is then choose another cell... The code below chooses the orientation of the boat, then chooses a random cell... but as you can see, no code for "across" to stop it choosing one too close to the side. Any ideas? Code: [Select] $orientation = rand(1,2); //get random orientation - 1 = down, 2 = across. if ($orientation == 1){ $multiply = 32; //cells till next row $max = 1024 - (32 * $boatlength); //prevents it from choosing a cell too close to the bottom $startcell = rand(1,$max); }else{ $multiply = 1; //across, so next cell $max = 1024; $startcell = rand(1,$max); } hi!, is it possible to use rand() to generate unique number that will be saved in a database as a primary key? Since i dont want to have numbers like 00001 incrementing on the table. They dont look like real account numbers... i need something like 45642 or 95452 and the like. thanks in advance. Hi, What I'm trying to do is create a script that generates a random list of cars whenever it is run. I have a list of available cars in a MySQL database. I'm just not sure how to get php to generate a list of, say, 20 cars, that are randomly picked from the cars in the database. I may also want to add other statistics like MPG (also already in the database). Can anyone show me how to do this? And is it possible to format the returned data in a table or div format? Thanks in advance Unk Hello, Do you guys have any idea how to start an Automatic Order Number System in PHP? I have an service Website, where you can purchase something, and i want after the redirect to "Success.php" to generate an order number, to be shown to the buyer and saved in Date Base for me. Any solutions helps. I´m beginner so don´t mind
Hey..
So lately I've been hooking up large requests to resque jobs in my application, for the purpose of not keeping the user(s) waiting for a longer period of time before they can continue using the application. At the same time, I have a frontend library & eventlistener alerting the users when any specific job was actually completed by the workers. I have realized however that in some cases, this doesn't pan out.
I love the idea of resque jobs, but my gut feeling is that I somehow lose control of the request I'm processing. The reason I'm posting this is because there's one part of my application that processes an insane amount of data, in a loop(!). Obviously this can take a long time, and that's to be expected. But when an error occurs along the way, I have no good way of logging it nor alerting the user about it.
Picture a scenario where a Worker is doing a Job that would take 2 minutes, and is 80% done, at which point it fails for whatever reason. How would you recommend something like this to be handled?
Obviously I get internal logs from the jobs the workers perform, but more specifically how would you catch the errors right from the script? Currently this is my setup...
try { ...//code that takes > 1min } catch(AppException $error) { ...//Internal code error, catch } catch(SeqDbException $dbError) { ..//DbError or Query } catch(SystemException $exception) { ..//More severe exceptions }Either I'm missing a catch, or I'm missing something else. The errors rarely occur as well, so it's not easy for me to debug it or re-create them. It's very dependent on the data that is being processed. My Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsane |