PHP - Score Keeps Incrementing? Cant See Why.
Hey guys, I have set a quiz up that pulls questions and answers from an array, every correct answer,.... score increments; however it is within a loop. Something must be wrong with the loop as it keep incrementing however i cant see why.
Any help would be great, The main aim what i am trying to do is have 5 questions answered and go to different page (different topic for 5 more questions) however keep the on going score. Hope this makes sense. If not ill try and clear it up. Thanks for all your help guys in advance, i appreciate it also not, i have a functions.php, questionsandanswers.php Code: [Select] <?php session_name("Question_Test"); session_start(); echo $_SESSION['score']; require_once('questionsandanswers.php'); require_once('functions.php'); if (!isset($_POST['submit'])) { $score = 0; $_SESSION['score'] = $score; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; if (isset($_SESSION['error'])) { unset($_SESSION['error']); $num = 0; } else { $score = 0; $_SESSION['score'] = $score; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; $num = 0; } } else { $num = (int) $_POST['num']; $postedanswers = str_replace("_"," ",$_POST['answers']); if ($postedanswers == $answers[$num]['0']) { $_SESSION['score'] ++; $_SESSION['correct'][] = $postedanswers; } else { $_SESSION['wrong'][] = $postedanswers; } if ($num < count($questions)-1) { $num++; } else { $last = true; $_SESSION['finished'] = 'yes'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>running an array</title> <?php if (!isset($last)) { echo "<script type=\"text/javascript\" src=\"form.js\"></script>"; } ?> </head> <body> <h1>Protection Section</h1> <?php if (!isset($last)){?> <h2>Questions <?php echo $num+1; ?>:</h2> <p><strong><?php echo $questions[$num]; ?></strong></p> <form id="questionBox" method="post" action="test1.php"> <?php $pattern = ' '; $replace = '_'; $shuffledAnswers = shuffle_assoc($answers[$num]); #var_dump($newanswers); foreach ($shuffledAnswers as $answer) { $answer2 = str_replace($pattern,$replace,$answer); echo "<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n"; echo "<label for=\"$answer2\">$answer</label></li>\n"; } ?> <input type="hidden" name="num" value="<?php echo $num; ?>" /> <input type="submit" id="submit" name="submit" value="Submit Answer" /></p> </form> <?php } else { echo "your final score is:</h2>\n <h3>{$_SESSION['score']}/20</h3><h4>Verdict:</h4>"; if($_SESSION['score'] <= 5) echo "<p id=\"verdict\"><span>S</span>everely <span>H</span>indered <span>I</span>n the <span>T</span>est!</p>\n"; if(($_SESSION['score'] > 5) && ($_SESSION['score'] <= 10)) echo "<p id=\"verdict\"><span>C</span>ould <span>R</span>ead <span>A</span>nd <span>P</span>ractice more.</p>\n"; if(($_SESSION['score'] > 10) && ($_SESSION['score'] <= 15)) echo "<p id=\"verdict\"><span>A</span>cronyms a<span>R</span>e <span>S</span>o <span>E</span>asy!</p>\n"; if($_SESSION['score'] > 15) echo "<p id=\"verdict\"><span>S</span>uper <span>A</span>cronym <span>S</span>pecialist</p>"; echo "<p id=\"compare\"><a href=\"test2.php\">Next Section! <img src=\"images/arrow.png\" /></a></p>"; } ?> </body> </html> Similar Tutorialshey guys. Hopefully someone can help me with this. I have been trying to figure out for a while now why the quiz score keeps incrementing even if i refresh the page. so far there is 2 quiz sections, firstly $_SESSION['score']; is incremented on every correct answer then this information is carried on to the second part of the quiz which increments $_SESSION['score'1]; However everytime a page is refreshed then it increments again. How can i get around this? Also note i have a questions and answers section (array of q's and a's) and a functions page. Any help would be great. Thanks in advance Lance Code: [Select] <?php session_name("Question_Test"); session_start(); $_SESSION['score']; require_once('questionsandanswers2.php'); require_once('functions.php'); if (!isset($_POST['submit'])) { $score1 = 0; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; if (isset($_SESSION['error'])) { unset($_SESSION['error']); $num = 0; } else { $score1 = 0; $_SESSION['score1'] = $score1; $_SESSION['correct'] = array(); $_SESSION['wrong'] = array(); $_SESSION['finished'] = 'no'; $num = 0; } } else { $num = (int) $_POST['num']; $postedanswers = str_replace("_"," ",$_POST['answers']); if ($postedanswers == $answers[$num]['0']) { $_SESSION['score1'] ++; $_SESSION['correct'][] = $postedanswers; } else { $_SESSION['wrong'][] = $postedanswers; } if ($num < count($questions)-1) { $num++; } else { $last = true; $_SESSION['finished'] = 'yes'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>running an array</title> <?php if (!isset($last)) { echo "<script type=\"text/javascript\" src=\"form.js\"></script>"; } ?> </head> <body> <?php if (!isset($last)){?> <h1>Detection Section</h1> <h2>Questions <?php echo $num+1; ?>:</h2> <p><strong><?php echo $questions[$num]; ?></strong></p> <form id="questionBox" method="post" action="test2.php"> <?php $pattern = ' '; $replace = '_'; $shuffledAnswers = shuffle_assoc($answers[$num]); #var_dump($newanswers); foreach ($shuffledAnswers as $answer) { $answer2 = str_replace($pattern,$replace,$answer); echo "<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n"; echo "<label for=\"$answer2\">$answer</label></li>\n"; } ?> <input type="hidden" name="num" value="<?php echo $num; ?>" /> <input type="submit" id="submit" name="submit" value="Submit Answer" /></p> </form> <?php } else { $_SESSION['finalscore'] = $_SESSION['score'] + $_SESSION['score1']; echo "your final score is:</h2>\n <h3>{$_SESSION['finalscore']}/20</h3><h4>Verdict:</h4>"; if($_SESSION['finalscore'] <= 5) echo "<p id=\"verdict\"><span>S</span>everely <span>H</span>indered <span>I</span>n the <span>T</span>est!</p>\n"; if(($_SESSION['finalscore'] > 5) && ($_SESSION['finalscore'] <= 10)) echo "<p id=\"verdict\"><span>C</span>ould <span>R</span>ead <span>A</span>nd <span>P</span>ractice more.</p>\n"; if(($_SESSION['finalscore']) && ($_SESSION['finalscore'] <= 15)) echo "<p id=\"verdict\"><span>A</span>cronyms a<span>R</span>e <span>S</span>o <span>E</span>asy!</p>\n"; if($_SESSION['finalscore'] > 15) echo "<p id=\"verdict\"><span>S</span>uper <span>A</span>cronym <span>S</span>pecialist</p>"; echo "<p id=\"compare\"><a href=\"test2.php\">Next Section! <img src=\"images/arrow.png\" /></a></p>"; } ?> </body> </html> Hello guys, i need some help in assigning a score to a word according to its occurrence in a group of sentences. Code: [Select] [php] $words="Hello, how are you?"; $sentences="Hello! I am fine. How about you? You look good."; [/php] now i'm trying to assign a score to each word in $words e.g Hello=1, how=1, are=0, you=2. I try to get a high score system to work. The problem is to write data to the txt file: The file adder.php contains: <?php if(array_key_exists('name',$_GET)==true and array_key_exists('score',$_GET)==true) { $name=$_GET['name']; $score=$_GET['score']; $file=fopen('highscore.txt','a'); fwrite($file,$name.';'.$score.';'); fclose($file); } header("Location: index.php"); // Replace index.php with the name (and, if not in the same folder, path) // of the page that will display the scores (see below) ?> I use this website: http://members.multimania.nl, so it looks like http://members.multimania.nl/mine/adder.php?name=winner&score=99 What am I doing wrong? I can't seem to figure out how to calculate the score the user gets when they hit the score button. I figured it would look something like this... $result_score = $right / 9 * 100.... but I've tried a few methods and I can't seem to figure out why its not working. Here is my code for the application.... Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Multiplication Test</title> </head> <body> <?php require_once('database.php'); define ('ROWS', 3); define ('COLS', 3); define ('MAX_NUMBER', 12); date_default_timezone_set('America/New_York'); if (isset($_POST['btn_score'])) { $result_name= $_POST['result_name']; $result_score= $_POST['result_score']; $result_score = / 9 * 100; $sql = "INSERT INTO results (result_name, result_score, result_date_time) VALUES ('$result_name','$result_score', NOW());"; $db->exec($sql); //print_r ($_POST); $time1 = $_POST['ts']; $time1_object = new DateTime($time1); $now = new DateTime(); $time_span = $now->diff($time1_object); $minutes = $time_span->format('%i'); $seconds = $time_span->format('%s'); $seconds+= $minutes * 60; echo "It took $seconds seconds to complete the test<hr />"; foreach ($_POST as $problem => $answer) { if ($problem <> "btn_score" && $problem <> "ts") { //echo "$problem -- $answer <br />"; $problem = explode('_', $problem); $num1 = $problem[2]; $num2 = $problem[3]; $right = $num1 * $num2; if ($answer != $right) { echo "$num1 * $num2 = $answer , The right answer is $right<br />"; } } } } ?> <h1>Multiplication Test</h1> <form name="lab5" method="post" action="lab5b.php"> <?php $now = new DateTime(); //echo $now->format('Y-m-d H:i:s'); echo "<input type='hidden' name='ts' value='" . $now->format('Y-m-d H:i:s') . "'>"; ?> <table border="1" cellspacing="5" cellpadding="5"> <?php $no_of_problems = 0; for ($row=0; $row<ROWS; $row++) { echo "<tr>"; for ($col=0; $col<COLS; $col++) { $num1 = mt_rand(1,MAX_NUMBER); $num2 = mt_rand(1,MAX_NUMBER); echo "<td>$num1 * $num2 </td>"; echo "<td><input type='text' size='2' name=${no_of_problems}_mult_${num1}_${num2}></td>"; $no_of_problems++; } echo "</tr>"; } $colspan = 2 * COLS; echo "<tr><td colspan=$colspan align='right'><input type='submit' value='Score' name='btn_score'></td></tr>"; ?> </table> <br> <br> <label for="result_name">Student Name:</label> <input type="text" id="result_name" name="result_name" /><br /> </form> <br> <br> </body> </html> I can't post/contribute in the code repo forum, so I'll post it here and maybe a mod will move it for me? Anyway, this is an algorithm for phonetic search scoring. Basically, it will evaluate a search string against an array of strings (list) and then return an array of ranked results from the list, in order of phonetic likeliness to the search string. In the returned array, the key is the score, the closer to 0, the more likely the phonetic match is; 0 being an exact match. Note: this is not pattern matching, this will match phonetic likeliness only. This is built around the English language as it stands, I am working on multi-lingual considerations. <?php /** * @NAME: Phonetic Search Score * @AUTHOR: Ryan Huff - MyCodeTree.com * @COPYRIGHT: (C)2011 * * The idea here is to supply a list (array) of strings (pressumably from a database * record set) and a single string. The class is designed to return an array of results * with X number of strings from the list that are the closest or equal phonetic * matches to the single string, ranked in order of closest phonetic match. * * The uniqueness of the Phonetic Search Score is the method in which it scores matches. The * scoring is based on the phonetic likeness of the single search string and each string * in the list, and is ranked accordingly. Scoring is not based on string length or * pattern matching like traditional REGEX pattern searching. * * A practical use for this would be a scenario where a user types in a search string, and * then the Phonetic Search Score provides a list of matches, ranked in order of their * phonetic likeliness to the search string. In the returned array, the key is the score, * the closer the key\score is to 0, the more likely the phonetic match is; 0 being an * exact match. * * An example use case is provided below. If you have any questions about the Phonetic * Search Score, you can contact me at support@mycodetree.com * */ class matcher { var $searchCriteria = NULL; //TEXT TO SEARCH FOR var $searchSet = array(); //SET TO SEARCH WITHIN var $numberOfMatches = 5; //NUMBER OF MATCHES TO RETURN var $removalChars = array('.','?','!','@','*','&','%','$','#',',',';',':','"','\''); //PUNCTUATION TO REMOVE var $returnMatches = array(); function scorer() { if (is_array($this->searchSet) && !empty($this->searchCriteria)) { $distal = array(); foreach ($this->removalChars as $val) { $replace[] = ""; } //REMOVE PUNCTUATION, CONVERT TO ALL LOWERCASE AND REMOVE LEADING AND ENDING SPACES $this->searchCriteria = trim(strtolower( str_replace($this->removalChars, $replace, $this->searchCriteria))); //GET METAPHONE KEY FOR SEARCH CRITERIA $scm = metaphone($this->searchCriteria); if ($this->numberOfMatches <= count($this->searchSet)) { for ($i=0; $i < count($this->searchSet); $i++) { $distal[levenshtein($scm, metaphone($this->searchSet[$i]))] = $this->searchSet[$i]; } } else { for ($i=0; $i < $this->numberOfMatches; $i++) { $distal[levenshtein($scm, metaphone($this->searchSet[$i]))] = $this->searchSet[$i]; } } ksort($distal); $this->returnMatches = $distal; } return false; } } /*INSTANTIATE CLASS*/ $score = new matcher(); /*EXAMPLE USE CASE*/ /*SETUP THE LIST OF STRING TO COMPARE THE SEARCH CRITERIA AGAINST*/ $score->searchSet = array( 'this is one item from a result set', 'this is another test item', 'more testing', 'Hello world, I am a test sentence.', 'So, do you have any mustard that I can borrow?' ); /*SETUP THE SEARCH CRITERIA*/ $score->searchCriteria = "Hello world, I am a test sentence."; /*FIRE THE SCORER METHOD (THIS METHOD WOULD BE EXPENSIVE TO CALL IN A LOOP, USE CAUTION)*/ $score->scorer(); /*DUMP THE RESULTS*/ print_r($score->returnMatches); ?> I am trying to create a full Scoreboard like the on the EPSN website. (The Red bar that shows the daily scores). So i created a DB called "scoreDB" I have like 30 sample scores in there.
What i want to create is a set of DIVS that will display the scores from the DB entries and refresh the scores every 10 seconds or so.
Righ now i can display the last score entered from the DB. But i can't make it change automaticly. So I started to think and I creted a Java scrip timer(see below)
My Issue i cant figure out how to make it work
Button line i want a divs that will diplay one score at a time and refresh every 10 seconds or so and display the next available record until it shows the last 10 and start diplaying the laters entry again. I will love to hear your sugestions or soluctions.
One DIV Sample below
<div class="score1" id="score1"> <?php mysql_select_db(scoredb) or die ("Couldn't not find DB"); $query = mysql_query("SELECT * FROM results ORDER BY IDResults DESC 1 "); while($row = mysql_fetch_assoc($query)) { $player1 = $row ["Player1"]; $score1 = $row ["Score1"]; $player2 = $row ["Player2"]; $score2 = $row ["Score2"]; echo $player1" . " " . $scr1 . " " . " " . " - " . " " . $player2" . " " . $scr2 ; } ?> </div> <br></br> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function countDown(secs, elem){ var element = document.getElementById(elem); element.innerHTML = "Please wait for "+secs+" seconds"; if(secs <1){ clearTimeout(timer); element.innerHTML = '<h2>Tournament is now Open!</h2>'; element.innerHTML += '<a href="#"> Click here now</a>'; } secs--; var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000); } </script> <div id="status"></div> <script type="text/javascript"> countDown(10,"status");</script> <p></p> I'm new to function and I can't figure how to update/result the score. I developed a game called Rock, Paper, & Scissors, so I can learn the function itself with a simple game for now. http://pastebin.com/9MB7ATnt Any tips or instruction would be much appreciated. Thanks. In my app, the users will take a multiplication test with 10 problems... I'm not sure how I would post the grade that the user got to the database. When the user finishes the test and hits score it should post their Name/Date & Time/ and Score to the database. I have the name and date & time working. Just not sure how I would approach the score. This is my application... It is small and simple to run in browser. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Lab 5</title> </head> <body> <?php require_once('database.php'); define ('ROWS', 3); define ('COLS', 3); define ('MAX_NUMBER', 12); date_default_timezone_set('America/New_York'); if (isset($_POST['btn_score'])) { $result_name=$_POST['result_name']; $sql = "INSERT INTO results (result_name, result_score, result_date_time) VALUES ('$result_name', 100, NOW());"; $db->exec($sql); //print_r ($_POST); $time1 = $_POST['ts']; $time1_object = new DateTime($time1); $now = new DateTime(); $time_span = $now->diff($time1_object); $minutes = $time_span->format('%i'); $seconds = $time_span->format('%s'); $seconds+= $minutes * 60; echo "It took $seconds seconds to complete the test<hr />"; foreach ($_POST as $problem => $answer) { if ($problem <> "btn_score" && $problem <> "ts") { //echo "$problem -- $answer <br />"; $problem = explode('_', $problem); $num1 = $problem[2]; $num2 = $problem[3]; $right = $num1 * $num2; if ($answer != $right) { echo "$num1 * $num2 = $answer , The right answer is $right<br />"; } } } } ?> <h1>Lab 5</h1> <form name="lab5" method="post" action="lab5b.php"> <?php $now = new DateTime(); //echo $now->format('Y-m-d H:i:s'); echo "<input type='hidden' name='ts' value='" . $now->format('Y-m-d H:i:s') . "'>"; ?> <table border="1" cellspacing="5" cellpadding="5"> <?php $no_of_problems = 0; for ($row=0; $row<ROWS; $row++) { echo "<tr>"; for ($col=0; $col<COLS; $col++) { $num1 = mt_rand(1,MAX_NUMBER); $num2 = mt_rand(1,MAX_NUMBER); echo "<td>$num1 * $num2 </td>"; echo "<td><input type='text' size='2' name=${no_of_problems}_mult_${num1}_${num2}></td>"; $no_of_problems++; } echo "</tr>"; } $colspan = 2 * COLS; echo "<tr><td colspan=$colspan align='right'><input type='submit' value='Score' name='btn_score'></td></tr>"; ?> </table> <br> <br> <label for="result_name">Student Name:</label> <input type="text" id="result_name" name="result_name" /><br /> </form> <br> <br> </body> </html> I'm in the process of creating a webage that shows latest scores and an updated league table for soccer/football matches like the bbc sports website does. I have the database set up with a form to update and display latest score all work well apart from if i update a score like the following teamA 1 teamB 0 it updates table to give teamA 3 points based on the current score however if teamA score again teamA 2 teamB 0 it updates table again but gives teamA another 3 points which is not correct so i need a way to stop it happening. thought about it for a while and only thing i can come up with is some maths to compare the values of score for each team and add/remove points as dependent on current score. Anyone got something similar to this I'm having troubles incrementing a date by one day using the following format: 11-17-2011 (m-d-Y) I am attempting to use the following script: Code: [Select] $time = strtotime("11-17-2011"); $final = date("m-d-Y", strtotime("+1 day", $time)); When i echo $final i get a whole different date "01-01-1970" Now if i switch the format around to the following: Code: [Select] $time = strtotime("2011-11-17"); $final = date("Y-m-d", strtotime("+1 day", $time)); and i echo $final i get the right date but in that format (2011-11-18). Is there a way i can get the date in the first format?(m-d-Y) Okay, for my bbcode parser, I run through [img tags with: Code: [Select] $text = preg_replace( "#\[img\](.+?)\[/img\]#ie" , "\\regex_check_image('\\1')" , $text ); It goes to my function regex_check_image: Code: [Select] function regex_check_image($url="") { if (!$url) return; $url = trim($url); $default = "[img]".$url."[/img]"; //-- mod_sec_update_131 begin $default = "[img]".str_replace( '[', '&# 091;', $url )."[/img]"; //-- mod_sec_update_131 end $image_count++; echo $image_count; exit; if ($image_count > 6) { message('You have posted to many Images'); exit; } if (preg_match( "/[?&;\<\[]/", $url)) { message('No Dynamic Images'); exit; } if (preg_match( "/javascript(\:|\s)/i", $url )) { message('No Dynamic Images'); exit; } // Is it a legitimate image? if (!preg_match( "/^(http|https|ftp):\/\//i", $url )) { message('No Dynamic Images'); exit; } // If we are still here.... $url = str_replace( " ", "%20", $url ); return "<img src='$url' border='0' />"; } Everything works fine, but for some reason, Code: [Select] $image_count++; echo $image_count; exit; if I have like 20 [img tags with images in them, I try to debug it, and echo it out, and it only shows "1" it should show how many [img tags I have, so I can echo out if somone is trying to spam images with the [img tag, any help? I am trying to keep track of how many times a page is loaded for debugging. Here is my code but it doesn't seem to work?! Code: [Select] <?php isset($counter) ? $counter++ : $counter=1; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Page A</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <h3>Add a Comment</h3> <form action="Processing.php" method="post"> <fieldset> <!-- Comment --> <label>Comment:</label><br /> <textarea cols="50" rows="15"><?php echo $counter; ?></textarea> <br /> <!-- Submit Form --> <input type="submit" name="addComment" id="addComment" value="Add a Comment"/> </fieldset> </form> </body> </html> What am I doing wrong? Debbie Hi all,
I'm having trouble attempting to increment values in an array...
$current = 5;
$next = array( IronMineList.php: Code: [Select] <?php include('buildingfile.php'); ?> <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'root'; $dbname = 'aosdb'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); $query="SELECT * FROM IMPrints"; $result=mysql_query($query); $num=mysql_num_rows($result); $i=0; $n=1; $j=0; $b=1; while($i<$num) { $name = mysql_result($result, $i, 'name'); $work = mysql_result($result, $i, 'workers'); $effi = mysql_result($result, $i, 'efficiency'); $cost = mysql_result($result, $i, 'cost'); $iron = mysql_result($result, $i, 'iron'); $copp = mysql_result($result, $i, 'copper'); $silv = mysql_result($result, $i, 'silver'); $titan = mysql_result($result, $i, 'titanium'); $gold = mysql_result($result, $i, 'gold'); $uran = mysql_result($result, $i, 'uranium'); $plat = mysql_result($result, $i, 'platinum'); $diam = mysql_result($result, $i, 'diamonds'); $oil = mysql_result($result, $i, 'oil'); $water = mysql_result($result, $i, 'water'); include('Iron.php'); $i++; $b++; $j++; $n++; } ?> Iron.php: Code: [Select] <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'root'; $dbname = 'aosdb'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); $queryj = "SELECT name FROM IMPrints"; $resultj = mysql_query($queryj); $Column = mysql_result($resultj, $j); $queryp = "SELECT * FROM IMBuilt WHERE idcol = $idcol"; $resultp = mysql_query($queryp); $Base = mysql_fetch_row($resultp); if(isset($_POST[""])) { if($_POST[""]) { $Badd = $Base[$b]+$_POST[""]; $queryi="UPDATE IMBuilt SET $Column=$Badd WHERE idcol = $idcol"; mysql_query($queryi); } } $queryf = "SELECT * FROM IMBuilt WHERE idcol = $idcol"; $resultf = mysql_query($queryf); $Basic = mysql_fetch_row($resultf); echo $i; ?> <p class="bd" id="built">| Built: <?php echo $Basic[$n]; ?> |</p> <form class="bd" method="post" action="IronMineList.php"><input type="text" name='[]'><input type="submit" value="Build"></form> What those 2 php documents do is display a list of iron mines a player in my game can build. It is supposed to create 1 form for each blueprint so that a player can add only to the number of that blueprint on their colony. The displays work perfectly. It creates 1 div that properly displays the stats of each mine in the database table. It also creates one form for each div. The problem I have is, I can only make the forms add 1 to all the buildings on a colony. The name='' value of the form and the $_POST[''] values do not increment with the rest of the code. I need a way to make each form apply only to the div which displays a specific mine. So where $i=0 the first form should only alter the value in imbuilt for the stats that are displayed by the rest of the div created for $i=0. Hi all - hoping somebody can see this clearer than me... Goal: to create a very simple shopping cart page that receives $_POST info and stores it as an array in a session variable so items will be displayed in cart on clients return to shopping cart page. Problem: I can get the array to display the first item that I add to the shopping cart but each susequest item just overwrites the first because it is using the same session variable name. How do I store the next product info in a DIFFERENT session variable and display it on the shopping cart page without writing over the first? I have two pages with products on them which need to submit orders to the shopping cart page. They use a simple form with these fields: <form method="post" action="cartaction.php"> <p> <input type="submit" name="submit" value="Buy" /> <input type="hidden" name="cartaction" value="add" /> <input type="hidden" name="item" value="coppercasserole" /> </p> </form> This is what I have so far on the cartaction page which can display the first product added to the cart: <?php //If form is submitted, call the function and save all data into the array $_SESSION['form'] if($_POST['submit'] == "Buy"){ setSessionVars(); } function setSessionVars() { if ( !isset($_SESSION['cart']) ) $_SESSION['cart'] = array(); $item = array(); foreach($_POST as $fieldname => $fieldvalue) { $item[$fieldname] = $fieldvalue; } $_SESSION['cart'] = $item; echo "<table> <tr> <td>" .'<img src="images/'.$item['item'].'.jpg"' . "<td/> <td>" . $item['item'] . "</td> <td>" . '<input type="text(30)" name="value" value="1" /> <input type="submit" name="puchasednum" value="Update This One Item" />' . "</td> </tr> </table>"; } ?> I am new to PHP and have hit a brick wall as to how to display each product array as a new session variable in the shopping cart. I would like to keep it as simple as possible as I am getting easily confused! Is there a way that I can increment the session variable with something like this: <?php //session counter $counter = count($_SESSION['cart']); if (($_POST['name'] !="")){ $counter = $counter + 1; $_SESSION['cart'][$counter] = array(); } ?> Or can I pass a field as a product ID and use this somehow to create a new session variable for each product or clear the post variables somehow? Any help would be much appreciated? Thanks Hey, just wondering what would be the best way of adding .1 to a string. For example: Code: [Select] $newversion = $currentversion + '0.0.1'; $newversion is taken from a db, lets say for this example it is 0.2.1 This code simply outputs 0.2 Any ideas? Thanks =) i have a slider that shows 2 images at a time. i did a query and got all my images names from the database to be in an array so i can go form index zero to the last image incrementing by +1 but not working. what it is doing now is displaying index[0] and index[1] in the first set of 2 images in the second set is displaying index[1] and index [2] in the third set is displaying index[2] and index[3] and so on... here's my query Code: [Select] require_once('connections.php'); mysql_select_db($dbname, $db); $sql = "SELECT * FROM table WHERE image IS NOT NULL LIMIT 6"; //limiting to six for testing only, will remove afterwords $results = mysql_query($sql, $db) or die(mysql_error()); $row = mysql_fetch_assoc($results); // $result2 = mysql_query("SELECT * FROM table WHERE image IS NOT NULL LIMIT 6"); $storeArray = Array(); while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) { $storeArray[] = $row2['image']; } ?> here's the html/php Code: [Select] <?php $index = 0;?> <?php do { ?> <div class="slide"> <div class="slidePromo"> <div class="promoImg"><a href="#"><img src="<?php echo $storeArray[$index];?>"/></a> </div> </div> <!--end slide--> <div class="slidePromo"> <div class="promoImg"><a href="#l"><img src="<?php echo $storeArray[++$index];?>"/></a></div> </div> </div> <!--end slide--> <?php } while ($row = mysql_fetch_assoc($results)); ?> 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 Basically I'm trying to set up a shopping cart using PHP & MySql (oh really!?) and I've gotten to the point where I need to insert the bought products into a database. Currently, at the checkout, there is a session which stores data for all of the products which have been added into the cart. From here I am just trying to create an order id code that is only relevant to this session. So in the database it would end up looking something like this: order_id = 001, product_id = 2, order_quantity = 3 order_id = 001, product_id = 4, order_quantity = 2 order_id = 001, product_id = 1, order_quantity = 5 order_id = 002, product_id = 2, order_quantity = 3 order_id = 002, product_id = 4, order_quantity = 2 order_id = 002, product_id = 1, order_quantity = 5 So I would be able to pull these results later by selecting the order relevant to the order_id. At least I think this is the easiest option for me. Every product which is put into the cart has a $_SESSION name of 'product_x', 'x' being the id associated with that product Any help? Hello sir, My name is Soji. I'm working on a php project on result transcript processing. I got to a stage where i need to rank student based on their score (Subject Position) and also Overall Position. I have tried all i could but i still don't get it I have a table called Subject position where with field (id, studentregNo, subjectid, levelid, armsid, yearid, total). what i want is if there is 3 student in a class and the first student score 50 in english and the second student score 45 and the third score 40. i want the system to tell me that the first student position in English is 1st and the second student position in English is 2nd and third student position in English is 3rd. So all this will be applicable to all subjects that the students in a particular level are offering.
Moreover, I need Rank student in a subject in that class, And this will work with each subject for each student in that class. |