Jump to content

PaulRyan

Members
  • Posts

    876
  • Joined

  • Last visited

  • Days Won

    4

Everything posted by PaulRyan

  1. if (mysqli_num_rows($chkEvent_res) > 0) { $event_title = "<br/>"; while ($ev = mysqli_fetch_array($chkEvent_res)) { $event_title .= "".stripslashes($ev["event_title"])."<br/>"; } mysqli_free_result($chkEvent_res); } else { $event_title = ""; } *Edit: I hate the code formatter.
  2. I would personally go with Jessica's solution, but it is also achievable via Javascript which has its drawbacks. I have had to use the following method once before: <?PHP if($_SERVER['REQUEST_METHOD'] == 'POST') { //### Set action array $actionArray = array(1 => 'first', 2 => 'second', 3 => 'third'); //### Set posted action and cast it as an integer $postedAction = (int)$_POST['action']; //### Check the posted action exists if(isSet($actionArray[$postedAction])) { echo 'Selected Action: '. $actionArray[$postedAction]; } else { echo 'No selected action.'; } } ?> <form method="POST" action="?"> <input type="hidden" name="action" id="action"> <div id="info"> <input type="submit" name="send" onclick="which(1);"> </div> <div id="info"> <input type="submit" name="send" onclick="which(2);"> </div> <div id="info"> <input type="submit" name="send" onclick="which(3);"> </div> </form> <script type="text/javascript"> function which(action) { document.getElementById('action').value = action; } </script>
  3. Form Code: <form method="GET" action="dl.php"> Key: <input type="text" name="key" value=""> <input type="submit" value="Submit Key"> </form> dl.php Code: <?PHP //### Preset valid key //### Should set this from a database of keys or something $validKey = 'CORRECTKEY'; //### Check to see if the $_GET key variable is present if(isSet($_GET['key'])) { $downloadKey = $_GET['key']; } else { $downloadKey = false; } //### Check to see if the download key matches valid key if($downloadKey == $validKey) { echo 'Key is valid.'; } else { echo 'Key is not valid.'; } ?>
  4. Form Code: <form method="GET" action="dl.php"> Key: <input type="text" name="key" value=""> <input type="submit" value="Submit Key"> </form> dl.php Code: <?PHP //### Preset valid key //### Should set this from a database of keys or something $validKey = 'CORRECTKEY'; //### Check to see if the $_GET key variable is present if(isSet($_GET['key'])) { $downloadKey = $_GET['key']; } else { $downloadKey = false; } //### Check to see if the download key matches valid key if($downloadKey == $validKey) { echo 'Key is valid.'; } else { echo 'Key is not valid.'; } ?>
  5. Try something like this: <?PHP //### Set this for testing purpose $statusItemCheck = 'jacket'; //### Path of images $imageValue = 'images/'; //### Array of items $stringArray = array('socks' => 'socks.png', 'hat' => 'hat.png', 'jacket' => 'jacket.png', 'boxers' => 'boxers.png' ); //### Check if the item exists in the array if(!isSet($stringArray[$statusItemCheck])) { echo 'Item does not exist.'; //### Item exists, add the image filename to image value } else { $imageValue .= $stringArray[$statusItemCheck]; echo $imageValue; } ?>
  6. Try this: <?PHP function miles2kms($miles) { $ratio = 1.609344; $kms = $miles * $ratio; return $kms; } //### If the form has been posted, process data if(strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') { //###Assign and santize data $miles = (float)$_POST['miles']; //### Convert value and assign it $converted = miles2kms($miles); } //### IF the converted value is set, display text if(isSet($converted)) { echo $miles .' miles, converts to '. $converted .' kilometres'; } ?> <form method="POST" action="?"> Miles: <input type="text" name="miles" /><br> <input type="submit" name="submit" value="Convert!" /> </form>
  7. Thanks a lot Barand for your query, worked like a charm! Also taught me something new Thanks Jessica for your help too, I apologize that I didn't ask the question correctly. I'll be sure to state my actual problem next time Regards, PaulRyan.
  8. I'll give that a go, I seriously did not know you could LEFT JOIN on 2 different columns. Learn something new everyday. Thanks, PaulRyan.
  9. Updated SQL: SELECT `npc`.`id`, `npc`.`name`, `npc`.`combat_level`, `pve`.`id` AS `attack_id`, IF(`pve`.`timestamp` != '', `pve`.`timestamp`, '0000-00-00 00:00:00') AS `attack_timestamp` FROM `world_npcs` AS `npc` LEFT JOIN (SELECT `id`,`defender_id`,`timestamp` FROM `log_pve_attacks` WHERE `attacker_id` = {$_SESSION['logged_in']} AND `timestamp` > NOW()-INTERVAL 10 MINUTE LIMIT 1) AS `pve` ON `pve`.`defender_id` = `npc`.`id` WHERE `npc`.`location_id` = 3 AND `npc`.`lr_coords` = 1 AND `npc`.`ud_coords` = 13 AND `npc`.`energy` > 0 ORDER BY `npc`.`id` DESC
  10. My bad, the problem is quite obvious, I am unable to retrieve the records from the database I want. I have stated the criteria at the top of the original post, I have tried a few different query modifications to do what I require but to no avail. I am thinking to join the attack log with the NPC selection query, then checking the time stamp (if any) against the current time stamp. I'll keep trying to see what I can come up with. Thanks, PaulRyan.
  11. Hello, I am creating an online RPG, and I'm stumped at the following: - Select all NPC's that match the current user co-ordinates and location ID - With each of those NPC's check the attack log to see if they have been attacked within the last 10 minutes by the logged in user - Only return the NPC's that have not been attacked within the last 10 minutes Tables are as follows: World NPC's CREATE TABLE IF NOT EXISTS `world_npcs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `combat_level` smallint(3) NOT NULL, `location_id` smallint(3) NOT NULL, `lr_coords` tinyint(2) NOT NULL, `ud_coords` tinyint(2) NOT NULL, `energy` tinyint(2) NOT NULL DEFAULT '20', `timestamp` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `world_npcs` -- INSERT INTO `world_npcs` (`id`, `name`, `combat_level`, `location_id`, `lr_coords`, `ud_coords`, `energy`, `timestamp`) VALUES (1, 'Beginner Battler', 2, 3, 1, 13, 20, '2013-01-15 00:00:00'), (2, 'Beginner Battler', 2, 3, 1, 13, 20, '2013-01-15 00:00:00'); Log PvE Attacks CREATE TABLE IF NOT EXISTS `log_pve_attacks` ( `id` int(11) NOT NULL AUTO_INCREMENT, `attacker_id` int(11) NOT NULL, `defender_id` int(11) NOT NULL, `winner_id` int(11) NOT NULL, `winner_cash_gain` int(11) NOT NULL, `winner_exp_gain` smallint(4) NOT NULL, `timestamp` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `log_pve_attacks` -- INSERT INTO `log_pve_attacks` (`id`, `attacker_id`, `defender_id`, `winner_id`, `winner_cash_gain`, `winner_exp_gain`, `timestamp`) VALUES (1, 1, 1, 1, 200, 6, '2013-01-27 21:17:47'), (2, 1, 1, 1, 200, 6, '2013-01-27 21:45:00'); My current SQL to return all NPC's in the same co-ordinates as the user: SELECT `npc`.`id`, `npc`.`name`, `npc`.`combat_level` FROM `world_npcs` AS `npc` WHERE `npc`.`location_id` = 3 AND `npc`.`lr_coords` = 1 AND `npc`.`ud_coords` = 13 AND `npc`.`energy` > 0 ORDER BY `npc`.`id` DESC - I have preset the location ID and user co-ordinates in the above SQL query. - The user ID is from $_SESSION['logged_id'] (This stores the users account id) - Attacker id will always be the logged in users ID as NPC's cannot attack the users, only users can attack the NPC's I would appreciate any help with this, I'll keep trying other methods, the ones I have tried so far haven't agreed with me. If anything else is needed, please let me know. Thanks, PaulRyan.
  12. <?PHP //### Start the session session_start(); //### MySQL credentials $DBhost = '127.0.0.1'; $DBuser = 'username'; $DBpass = 'password'; $DBname = 'database name'; //### Connect to the database $connect = mysql_connect($DBhost,$DBuser,$DBpass); mysql_select_db($DBname,$connect); //### If the form is submitted, process data if($_SERVER['REQUEST_METHOD'] == 'POST') { //### Assign data $name = mysql_real_escape_string($_POST['name']); $message = mysql_real_escape_string($_POST['message']); //### Validation if(!$name) { echo 'Please enter your name'; } else if(!$message) { echo 'Please enter a message.'; } else { $addShoutQuery = "INSERT INTO `shout` (`name`, `post`) VALUES ('{$name}', '{$message}')"; $addShout = mysql_query($addShoutQuery); if(!mysql_affected_rows()) { echo 'Unable to add message'; } else { $_SESSION['message'] = 'Message has been added'; header('Location: ?'); exit; } //### End query check } //### End validation } //### End post process //### Retrieve shouts from database $selectShoutsQuery = "SELECT `name`, `post` FROM `shout` ORDER BY `id` DESC"; $selectShouts = mysql_query($selectShoutsQuery) or die(mysql_error()); if(!mysql_num_rows($selectShouts)) { echo 'No messages posted.'; } else { $shoutBox = ''; //### Display messages from database while($row = mysql_fetch_assoc($selectShouts)) { $shoutBox .= "{$row['name']}: {$row['post']} <br>".PHP_EOL; } } if(isSet($_SESSION['message'])) { echo $_SESSION['message'] .'<br>'.PHP_EOL; unset($_SESSION['message']); } ?> <form method="POST" action="index.php"> Name: <input type="text" name="name" value=""> <br> Message: <input type="text" name="message" value=""> <br> <input type="submit" value="Post Message"> </form> <br> <?PHP echo $shoutBox;?> Try that out. Should probably look into MySQLi also, instead of MySQL, not much to change in the code.
  13. You shouldn't really echo or print from a function as it doesn't do as you expect. Return the value from the function and assign it to a variable, then use that variable to display its value. <?PHP function writeValue($value) { //### Check to make sure an array was provided if(!is_array($value)) { $finalOutput = 'You did not provide an array.'; //### If an array is provided add each element to the output } else { $finalOutput = ''; //### Foreach element add it to the output foreach($value AS $output) { $finalOutput .= $output . PHP_EOL; } } //### Return the output, don't echo return $finalOutput; } //### Echo output from function $functionOutput = writeValue(array('one','two','three','four')); echo nl2br($functionOutput); ?>
  14. Thanks for the suggestions. Firstly, I myself am not too keen on OOP, I've heard many postive things about it, I just cannot get my head around it. This is something I will consider though, so thanks. Secondly, thanks for the max(), I didn't think to use it in such a way. Thirdly, I will do as you say, I always forget to use true/false, been so used to using 1 and 0, I naturally associate the numbers with true/false in my head, so I use that format.
  15. I have created a battle script for an online RPG I am creating, I've come up with the following, which does exactly what I need. I would like to know if there is anything you would change, or anything that could be done a different/better way? The battle should include the following: - Highest agility attacks first (random number between 90%-110% of current agility, gives lower levels a chance to attack first) - A chance to guard the attack using the guard value (5% chance currently) - A chance to hit a power strike using the power strike value (5% chance currently) will hit 150%-200% of players attack power. - If its a hit and not a power strike, a value between 95%-105% of players attack power. I have filled the attacker and defender arrays with sample data, this will be retrieved from the database before the battle and replaced with real values which will be subject to change if skills/spells are active, items that are worn and special effects from various quests etc. The reason for the attack array, is not only for displaying, but it makes it simpler to view/edit as well as the fact I can access the stats of the battle via the array, for successful attacks/blocks/power strike etc. for which I am wanting to store as everyone loves stats, and those will be pretty cool to view over an accounts life time. Side note: I hate this code plugin, messes my code indenting/spacing. <?PHP //### Define attack ranges $attackRanges = array('normal_attack_low' => 0.95, 'normal_attack_high' => 1.05, 'power_attack_low' => 1.5, 'power_attack_high' => 2.0, 'agility_range_low' => 0.9, 'agility_range_high' => 1.1 ); //### Assign the attacking players details $attacker = array('name' => 'Player 1', 'attack' => 100, 'health' => 400, 'power_strike' => 5.0, 'guard' => 5.0, 'agility' => 500 ); //### Assign defending players details $defender = array('name' => 'Player 2', 'attack' => 100, 'health' => 400, 'power_strike' => 5.0, 'guard' => 5.0, 'agility' => 500 ); //### Randomly generate each players agility, with a percentage increase/decrease $attacker['agility'] = mt_rand($attacker['agility']*$attackRanges['agility_range_low'], $attacker['agility']*$attackRanges['agility_range_high']); $defender['agility'] = mt_rand($defender['agility']*$attackRanges['agility_range_low'], $defender['agility']*$attackRanges['agility_range_high']); //### Work out who attacks first $attackTurn = $attacker['agility'] >= $defender['agility'] ? '1' : '2'; //### While both players are still alive, alternate who attacks while($attacker['health'] > 0 && $defender['health'] > 0) { //### Attacking players turn to attack if($attackTurn == 1) { //### Does the defending player guard the attack? $defensiveGuard = mt_rand(0, 10000); $defensiveGuardRange = array('high' => 5000*((100+$defender['guard'])/100), 'low' => 5000*((100-$defender['guard'])/100) ); //### If the defensive guard is within the defensive range, the attack is blocked if($defensiveGuard >= $defensiveGuardRange['low'] && $defensiveGuard <= $defensiveGuardRange['high']) { $attackPower = mt_rand($attacker['attack']*$attackRanges['normal_attack_low'], $attacker['attack']*$attackRanges['normal_attack_high']); $attackHit = 0; $powerStrike = 0; //### If the defensive guard is not within the defensive range, the attack is not blocked } else { //### Is the attack a power strike? $offensiveStrike = mt_rand(0, 10000); $offensiveStrikeRange = array('high' => 5000*((100+$attacker['power_strike'])/100), 'low' => 5000*((100-$attacker['power_strike'])/100) ); //### If the power strike is within the power strike range, perform power strike if($offensiveStrike >= $offensiveStrikeRange['low'] && $offensiveStrike <= $offensiveStrikeRange['high']) { $attackPower = mt_rand($attacker['attack']*$attackRanges['power_attack_low'], $attacker['attack']*$attackRanges['power_attack_high']); $attackHit = 1; $powerStrike = 1; //### If the power strike is not within the power strike range, perform normal strike } else { $attackPower = mt_rand($attacker['attack']*$attackRanges['normal_attack_low'], $attacker['attack']*$attackRanges['normal_attack_high']); $attackHit = 1; $powerStrike = 0; } } //### Make sure the defenders health does no go below 0 if($attackHit == 1) { if(($defender['health']-$attackPower) < 0) { $defender['health'] = 0; } else { $defender['health'] -= $attackPower; } } //### Add the attack turn to the attack array $attackArray[] = array('whos_turn' => $attacker['name'], 'attack_hit' => $attackHit, 'power_strike' => $powerStrike, 'attack_power' => $attackPower, 'defend_health' => $defender['health'] ); //### Define who won the battle $winner = $attacker['name']; //### Alternate to defenders attack turn $attackTurn = 2; //### Defending players turn to attack } else { //### Does the attacking player guard the attack? $offensiveGuard = mt_rand(0, 1000); $offensiveGuardRange = array('high' => 500*((100+$attacker['guard'])/100), 'low' => 500*((100-$attacker['guard'])/100) ); //### If the offensive guard is within the offensive range, the attack is blocked if($offensiveGuard >= $offensiveGuardRange['low'] && $offensiveGuard <= $offensiveGuardRange['high']) { $attackPower = mt_rand($defender['attack']*$attackRanges['normal_attack_low'], $defender['attack']*$attackRanges['normal_attack_high']); $attackHit = 0; $powerStrike = 0; //### If the offensive guard is not within the offensive range, the attack is not blocked } else { //### Is the attack a power strike? $defensiveStrike = mt_rand(0, 10000); $defensiveStrikeRange = array('high' => 5000*((100+$defender['power_strike'])/100), 'low' => 5000*((100-$defender['power_strike'])/100) ); //### If the power strike is within the power strike range, perform power strike if($defensiveStrike >= $defensiveStrikeRange['low'] && $defensiveStrike <= $defensiveStrikeRange['high']) { $attackPower = mt_rand($defender['attack']*$attackRanges['power_attack_low'], $defender['attack']*$attackRanges['power_attack_high']); $attackHit = 1; $powerStrike = 1; //### If the power strike is not within the power strike range, perform normal strike } else { $attackPower = mt_rand($defender['attack']*$attackRanges['normal_attack_low'], $defender['attack']*$attackRanges['normal_attack_high']); $attackHit = 1; $powerStrike = 0; } } //### Make sure the defenders health does no go below 0 if($attackHit == 1) { if(($attacker['health']-$attackPower) < 0) { $attacker['health'] = 0; } else { $attacker['health'] -= $attackPower; } } //### Add the attack turn to the attack array $attackArray[] = array('whos_turn' => $defender['name'], 'attack_hit' => $attackHit, 'power_strike' => $powerStrike, 'attack_power' => $attackPower, 'defend_health' => $attacker['health'] ); //### Define who won the battle $winner = $defender['name']; //### Alternate to attackers attack turn $attackTurn = 1; } } echo '<pre>'; foreach($attackArray AS $attackTurn) { if($attackTurn['attack_hit'] == 0) { echo $attackTurn['whos_turn'] .' attacked for '. number_format($attackTurn['attack_power']) .' but the attack was blocked ['. $attackTurn['defend_health'] .']<br>'; } else if($attackTurn['power_strike'] == 1) { echo 'Power Strike! '. $attackTurn['whos_turn'] .' attacked for '. number_format($attackTurn['attack_power']) .' ['. $attackTurn['defend_health'] .']<br>'; } else { echo $attackTurn['whos_turn'] .' attacked for '. number_format($attackTurn['attack_power']) .' ['. $attackTurn['defend_health'] .']<br>'; } } echo '<br>'. $winner .' is victorious.'; ?>
  16. Try something like this: <?PHP //### Function to display menu function displayMenu($menu='') { //### Check to see which menu to show using is else if($menu == 'home') { $menuHTML = '<ul> <li><a href="#">Home Link</a></li> <li><a href="#">Home Link</a></li> </ul>'; } else if($menu == 'profile') { $menuHTML = '<ul> <li><a href="#">Profile Link</a></li> <li><a href="#">Profile Link</a></li> </ul>'; } else { $menuHTML = '<ul> <li><a href="#">Default Link</a></li> <li><a href="#">Default Link</a></li> </ul>'; } //### Return select menu return $menuHTML; } //### Displays default links echo displayMenu(); //### Displays home links echo displayMenu('home'); //### Displays profile links echo displayMenu('profile'); ?>
  17. Please note, that if you are comparing numbers, you should cast the $product_id as an (int) and remove the quotes around the comparison number E.G. "24" should just be 24. Try this: <?PHP if(!isSet($_GET['product_id'])) { //### You could declare a default product id number? //### For now we're showing a default error message echo 'You have not declared a product ID number.'; exit; } else { //### Assign and cast product id $product_id = (int)$_GET['product_id']; } if($product_id == 23 ) { //### Include file include('phpgd/index.php'); } else if($product_id == 24) { //### Display HTML Form otherwise echo <<<HTML_FORM <div class="preview"> <img src="phpgd/scripts/server-side.php" width="400" height="244" /> </div> <form id="realtime-form" action="#" method="post"> <fieldset> <legend>Business Card Builder Form</legend> <ol> <li class="left"> <fieldset> <legend class="accessibility">Company Information</legend> <ol> <li> <label for="company-name">Company name</label> <input type="text" id="company-name" name="companyName" value="Company Name" /> </li> <li> <label for="company-slogan">Company slogan:</label> <input type="text" id="company-slogan" name="companySlogan" value="Company Slogan" /> </li> <li> <label for="business-address">Business address</label> <textarea id="business-address" name="businessAddress">1234 Main Street Suite 101 City, ST 12345</textarea> </li> </ol> </fieldset> </li> <li class="right"> <fieldset> <legend class="accessibility">Contact Information and Description</legend> <ol> <li> <label for="full-name">Full name</label> <input type="text" id="full-name" name="fullName" value="John Smith" /> </li> <li> <label for="job-title">Job title</label> <input type="text" id="job-title" name="jobTitle" value="Job Title" /> </li> <li> <label for="primary-phone">Primary phone</label> <input type="text" id="primary-phone" name="phoneOne" value="P: 954-555-1234" /> </li> <li> <label for="secondary-phone">Secondary phone</label> <input type="text" id="secondary-phone" name="phoneTwo" value="P: 954-555-5678" /> </li> <li> <label for="email-address">Email address</label> <input type="text" id="email-address" name="emailAddress" value="john@company.com" /> </li> <li> <label for="web-address">Web address</label> <input type="text" id="web-address" name="siteUrl" value="websiteurl.com" /> </li> </ol> </fieldset> </li> </ol> </fieldset> </form> HTML_FORM; } ?>
  18. Unfortunately no-one will just create this for you. Give it a go yourself and write some code, if it doesn't work then come back and we'll do our best to help out. If you don't want to give it a go yourself, then you should post in the PHP Freelancing section and pay someone to complete this for you.
  19. Thanks Scootstah and KevinM1 for your insight input, will take heed of your comments
  20. I will definitely have a look at those, I agree most of the online tutorials aren't the best, they never were for prodecural either. I have wanted to have a look into OOP for sometime, but could never bring myself to spend the time researching and learning if it wasn't going to be beneficial, when it could be time spent working.
  21. Well spotted, but I'm asking for your opinions on OOP, not your opinion on my post, or my current research (or lack of). I don't want to waste time researching something that I feel wouldn't benefit me, if someone had a few valid points as to why they use it, or prefer it, then it would lead me to look into it more.
  22. Admittedly, I haven't read as much on it as I have wanted, mainly because I don't see the advantage of using OOP.
  23. I've been developing with PHP for about 6-7 years now, since I was around 13-14. I've always used the procedural coding style when ever I've undertaken a project, whether it be for myself, or freelancing. I've read up on OOP and it's advantages/disadvantages and whatnot, but I just cannot grasp how it can be used effectively. As far as I see it, its a bunch of functions wrapped in a class, which is loosely similar to just normal PHP functions within procedural coding. Why would someone use OOP over procedural? I would like some individual input on this, because I would like to better my knowledge of OOP and maybes start using it for future projects of my own, till I am comfortable enough to use it for freelance work. Just looking for your insight to the benefits of OOP, and your honest opinion on whether its worth learning and why. Thanks in advance, Paul.
  24. You could always use the attribute readonly for example: <input type="text" name="test" readonly="readonly" value="TESTER">
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.