PHP - Displaying High Scores - Highest Score Per User
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 Similar TutorialsHello, 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"; } ?> 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 have mysql select query shown below retrieving data from a database:
$sql = " SELECT student, sum( test_score ) as score FROM test INNER JOIN level ON test.level_id = level.level_id GROUP BY student" $result = $mysqli->query($sql, MYSQLI_STORE_RESULT); if($result) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { var_dump($row); } }On inspection of the retrieved array with var_dump(), i have these result below: array (size=2) 'John' => string 'English' (length=2) 'Score' => string '20' (length=3) array (size=2) 'Mary' => string 'Math' (length=3) 'Score' => string '35' (length=3) array (size=2) 'Samuel' => string 'Physics' (length=3) 'Score' => string '5' (length=3)How do I get at and print out the highest score from this set of array values within this context. I tried this echo max($row['count']) but i understandably got this feedback: Warning: max(): When only one parameter is given, it must be an array Thanks. Hello, I need to set a CSS class for the highest number in a MySQL column, and the second highest. So for instance I have a column named scores. I would want the <td> with highest scores to be <td.Winner> and the second highest to be <td. RunnerUp>. I know how to set the css part up, so just need help with creating a function. I did something similar to set the background of table cells based on the text data and that looked like this. function cssfromdate($date) { $class = array('December_January' => 'January', 'March_April' => 'March'); return $class[$date]; } while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['last_name'] . "</td>\n"; echo "<td>" . ucwords($row['first_name']) . "</td>\n"; echo "<td class=\"".cssfromdate($row['Class_Date'])."\">".$row['Class_Date']."</td>\n"; echo "</tr>"; } I am hoping I can accomplish what I need to doing something similar. I need help getting user comments from my database and displaying them in a format like you'd see in an online newspaper where each user's comments are displayed one after the other like this... Quote --------------------- By John Doe 8:30 p.m. on Sept 1, 2011 I really liked Debbie's article and encourage others to read it! --------------------- By Sally Peters 11:00 a.m. on Aug 30, 2011 I had the same thing happen to me!! --------------------- Here is the code I have on my "article.php" page below where I generate my Article... Code: [Select] // ********************** // Build Comments Query * // ********************** // Build query. $q = 'SELECT m.first_name, c.created_on, c.body, c.status FROM member AS m INNER JOIN comment AS c ON m.id = c.member_id WHERE article_id=?'; // Prepare statement. $stmt = mysqli_prepare($dbc, $q); // Bind variable. mysqli_stmt_bind_param($stmt, 'i', $articleID); // Execute query. mysqli_stmt_execute($stmt); // Store result-set. mysqli_stmt_store_result($stmt); // **************************** // Check for Comments Record. * // **************************** if (mysqli_stmt_num_rows($stmt)>=1){ // Comment in Database. $commentExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $firstName, $createdOn, $body, $status); // Fetch record. mysqli_stmt_fetch($stmt); } Is it correct that mysqli_stmt_store_result($stmt); stores the entire query results? Where does it do that? Some hidden MySQL object in memory? How do I get the query results into a format where I can iterate through each record and display it? Thanks, Debbie Hi guys Do you guys know if possible to open an external URL without actually displaying this to the user? We have a service where we wish to open an external URL which triggers sending out an SMS to the user. However..we cannot display the url opened to the user as it shows our username etc with the sms provider. basically the url looks like this: https://www.smsprovider.com/username=OurUsername&password=******&smsMsg_to_send=blablablablabla Is it possible to "trigger" this URL without letting our users see it? Thanks in advance for any help you may provide i need to display the fullname and email of the logged in user. <?php session_start(); mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("db_register") or die(mysql_error()); $query = "SELECT` fullname`, `email` FROM `members` WHERE `username`='".$_SESSION['user']."' LIMIT 1"; if($doQuery = mysql_query($query)) { if(mysql_num_rows($doQuery)) { $user = mysql_fetch_assoc($doQuery); print_r($user); } else { echo 'No result returned for the query: '.$query; } } else { echo 'The following query failed: '.$query; } $id = $user['id']; $fullname = $user['fullname']; $email = $user['email']; } ?> <br> Fullname : <?php echo $fullname; ?> <br> Email : <? echo $email; ?> ?> HELP please . Hello, I'm trying to build a registration/login system. I managed to set it up but i need that for the user when he/she is logged in to display his own information and to manage to edit them, First i need to display them, because i seem to not be doing it.. i know it's easy in principal but i am really new at this... So here is my code: The login.php page Code: [Select] <?php include ('database_connection.php'); if (isset($_POST['formsubmitted'])) { // Initialize a session: session_start(); $error = array();//this aaray will store all error messages if (empty($_POST['e-mail'])) {//if the email supplied is empty $error[] = 'You forgot to enter your Email '; } else { if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) { $Email = $_POST['e-mail']; } else { $error[] = 'Your EMail Address is invalid '; } } if (empty($_POST['Password'])) { $error[] = 'Please Enter Your Password '; } else { $Password = $_POST['Password']; } if (empty($error))//if the array is empty , it means no error found { $query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL"; $result_check_credentials = mysqli_query($dbc, $query_check_credentials); if(!$result_check_credentials){//If the QUery Failed echo 'Query Failed '; } if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull { // A match was made. $_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);//Assign the result of this query to SESSION Global Variable header("Location: page.php"); }else { $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect'; } } else { echo '<div class="errormsgbox"> <ol>'; foreach ($error as $key => $values) { echo ' <li>'.$values.'</li>'; } echo '</ol></div>'; } if(isset($msg_error)){ echo '<div class="warning">'.$msg_error.' </div>'; } /// var_dump($error); mysqli_close($dbc); } // End of the main Submit conditional. ?><!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>Login Form</title> <style type="text/css"> body { font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; font-size:12px; } .registration_form { margin:0 auto; width:500px; padding:14px; } label { width: 10em; float: left; margin-right: 0.5em; display: block } .submit { float:right; } fieldset { background:#EBF4FB none repeat scroll 0 0; border:2px solid #B7DDF2; width: 500px; } legend { color: #fff; background: #80D3E2; border: 1px solid #781351; padding: 2px 6px } .elements { padding:10px; } p { border-bottom:1px solid #B7DDF2; color:#666666; font-size:11px; margin-bottom:20px; padding-bottom:10px; } a{ color:#0099FF; font-weight:bold; } /* Box Style */ .success, .warning, .errormsgbox, .validation { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; } .success { color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } .warning { color: #9F6000; background-color: #FEEFB3; background-image: url('images/warning.png'); } .errormsgbox { color: #D8000C; background-color: #FFBABA; background-image: url('images/error.png'); } .validation { color: #D63301; background-color: #FFCCBA; background-image: url('images/error.png'); } </style> </head> <body> <form action="login.php" method="post" class="registration_form"> <fieldset> <legend>Login Form </legend> <p>Enter Your username and Password Below </p> <div class="elements"> <label for="name">Email :</label> <input type="text" id="e-mail" name="e-mail" size="25" /> </div> <div class="elements"> <label for="Password">Password:</label> <input type="password" id="Password" name="Password" size="25" /> </div> <div class="submit"> <input type="hidden" name="formsubmitted" value="TRUE" /> <input type="submit" value="Login" /> </div> </fieldset> </form> Go Back to <a href="#">Account Verification on sign up</a> </body> </html> This is the page's code where user is redirected after login Code: [Select] <?php ob_start(); session_start(); if(!isset($_SESSION['Username'])){ header("Location: login.php"); } ?> <!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>Member Area </title> <style type="text/css"> .success { border: 1px solid; margin: 0 auto; padding:10px 5px 10px 60px; background-repeat: no-repeat; background-position: 10px center; font-weight:bold; width:450px; color: #4F8A10; background-color: #DFF2BF; background-image:url('images/success.png'); } </style> </head> <body> <div class="success">Welcome , <?php echo $_SESSION['Username'] ; ?></div> <? $b = time (); $date1 =date( "Y-m-d;h:i:s" , mktime(date("h")+6, date("i"), date("s"), date("m") , date("d"), date("Y"))); $str_time = "&receivedtimestamp="; $str_msg = "&msg=bkt"; $str_from = "from="; ?> <a href="http://testext.i-movo.com/api/receivesms.aspx?<?echo $str_from;?><?echo $_SESSION['phone'];?><?echo $str_time;?><?echo $date1;?><?echo $str_msg;?>">Get a Cupon</a> </br> <?php echo $_SESSION['Email'] ; ?> </br> <?php echo $_SESSION['phone'] ; ?> <p><strong>My Account</strong></p> <a href="myaccount.php">My Account</a><br> <a href="mysettings.php">Settings</a><br> <a href="logout.php">Logout </a> </body> </html> And finally the database structure is this one ... Code: [Select] CREATE TABLE IF NOT EXISTS `members` ( `Memberid` int(10) NOT NULL AUTO_INCREMENT, `Username` varchar(20) NOT NULL, `Email` varchar(50) NOT NULL, `Password` varchar(10) NOT NULL, `phone` varchar(25) NOT NULL, `Activation` varchar(60) DEFAULT NULL, PRIMARY KEY (`Memberid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ; Please help me with this because i'm going mad Hi, I got this code which is meant to display the login details of the person that is logged in, however it just displays the details of the last person in the mysql table. I have set up some test logins, so if I login as paul1 the details for paul3 are displayed...confused Anyway, here is the page which displays the details Code: [Select] <?php session_start(); // This checks to make sure the session variable is registered // WARNING: DO NOT DELETE THE FOLLOWING LINE OF TEXT if( isset($_SESSION['username']) && isset($_SESSION['sid'])) { // You are free to edit the following code to suit your requirements include_once("../../data/server.php"); include_once("../../lib/userdata.php"); // THIS BIT WORKS AND DISPLAYS THE USERNAME $data = mysql_query("SELECT * FROM members") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { include("../../lib/userinfo.php"); //////////////////////////////////////////// WARNING: YOU SHOULD NOT EDIT ANYTHING ABOVE THIS LINE //////////////////////////////////////////////////////// ECHO <<<PAGE <!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=iso-8859-1" /> <title>$siteName</title> <link rel="stylesheet" href="../../userstylesheet.css" type="text/css" /> </head> <div id="page"> <img alt="" src="../../images/leftCurve" height="6" width="6" id="left" /> <img alt="" src="../../images/rightCurve.gif" height="6" width="6" id="right" /> <div id="pageName"> <h1>$siteName</h1> </div> <div id="pageNav"> <div id="sectionLinks"> <a href="profile.php?username=$username">My Profile</a> <a href="modify.php?username=$username">Personal Details</a> <a href="message.php?username=$username">Messages</a> <a href="../../logout.php?username=$username">Logout</a></div> </div> <div id="content"> <div class="feature"> <h2>Welcome $username </h2> <p>This is the demonstration home.html template. You are free to edit this or any of the other templates to suit your own needs. </p> <p>This is the first page your member will see once they have logged in. </p> <p>If you look at the code for this page, you will see that all HTML code is placed between the ***PAGE and PAGE; tags. Please note that the three * should be replaced with the < character. This format must be kept to ensure that the user variables work. Changing this format may result in errors being returned.</p> <p>You may call member information using the $ tag and the variable name eg $ firstname without the space, will show the members first name, such as $firstname</p> <p>For any information please visit our site http://www.membersitemaker.co.uk. User guides will be added shortly and the forum will soon be full of help. </p> </div> </div> <div id="information"> <a href="#">About Us</a> | <a href="#">Site Map</a> | <a href="#">Privacy Policy</a> | <a href="#">Contact Us</a> | ©2011 $siteName </div> </div> </body> </html> PAGE; } //////////////////////////////////////// WARNING: DO NOT DELETE ANYTHING BELOW THIS LINE ////////////////////////////////////////////////////////// } else { // This will redirect the user to the login page if the session variables do not exist header( "Location: ../../../login.html" ); } ?> And here is the code for userdata.php Code: [Select] <?php // Decode sitename function decode_variable(&$siteName) { $siteName = urldecode($siteName); $siteName = str_replace('%20',' ',$siteName); return $siteName; } decode_variable($siteName); // Connnect to MySQL database include_once("../../data/mysql.php"); $mysqlPassword = (base64_decode($mysqlpword)); $db = mysql_connect("$localhost", "$mysqlusername", "$mysqlPassword") or die ("Error connecting to database"); mysql_select_db("$dbname", $db) or die ("An error occured when connecting to database"); // Carry out MySQL query ?> and userinfo.php Code: [Select] <?php $username = $info['username']; $firstname = $info['firstname']; $lastname = $info['lastname']; $address = $info['address']; $town = $info['town']; $county = $info['county']; $postcode = $info['postcode']; $email = $info['email']; $birth_year = $info['birth_year']; $country = $info['country']; $telephone_number = $info['telephone_number']; $mobile_number = $info['mobile_number']; $nickname = $info['nickname']; As always, your help is much appreciated Paul Hi all, I'm new to PHP and just looking for any advice anyone might have on the following problem I'm having. I have created a database and tables for registering and logging in users. Each record has three different User Types (or roles): 1, 2 and 3. Once the session has started, I would like to make certain menu items available to certain User Types. I suppose it is some sort of if...elseif statement such as: <?php if($UserType==1) echo {"<p>Menu1</p>"} elseif($UserType==2) echo {"<p>Menu2</p>"} elseif($UserType==3) echo {"<p>Menu3</p>"}; ?> Would anybody be able to point me in the right direction? I'd really appreciate any help at all. HOw to get the AVERAGE of my entire database? $query = "SELECT ROUND(AVG(scores)) FROM table"; Thanks! Bickey 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 ? 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 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> hey 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> 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> 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 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> |