santaowns Posted July 11, 2009 Share Posted July 11, 2009 I coded a timer that shows the time on the current page. This timer is in javascript but i need it to go into a mysql database. How can i accomplish this with php? this code is for a form, as you can see in the div content i did not include it. Below is my code <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title><?=$quiz_question?></title> <style type="text/css" media="screen">@import "quiz.css";</style> </head> <body onload="timer()"> <center><img src="images/logo.gif" height=85 width=240></center> <div id="Content"> [highlight]There is a simple form here with a submit button[/highlight] </div> <div id="Menu"> <? if($logged_in){ echo 'Logged in as '.$_SESSION['username'].', <a href="logout.php">logout</a>'; }else{ echo 'Not logged in.'; displayLogin(); } ?><br> <a href="#">Pause Training for Patrol</a><br> Time on this module: <style type="text/css"> #time{ font-size:12pt; } </style> <script type="text/javascript"> var digiclock = "00:00:00"; i = 0; function timer() { var digiformat = ""; if(i>3599) { var H = Math.floor(i/3600); } else { var H = 0; } var M = i - (H*3600) if(M>59) { M = Math.floor(M/60) } else { M = 0 } var S = i - (M*60) if(H<10) { H = "0"+H; } if(M<10) { M = "0"+M; } if(S<10) { S = "0"+S; } document.getElementById('time').innerHTML = H+":"+M+":"+S; setTimeout('timer()', 1000); i++; } </script> <div id="time">90</div> </div> </body> </html> I would also like the "Pause for security patrol" link to pause the timer, any insight on this would be appreciated as well. Quote Link to comment Share on other sites More sharing options...
.josh Posted July 11, 2009 Share Posted July 11, 2009 http://www.phpfreaks.com/tutorial/php-basic-database-handling Quote Link to comment Share on other sites More sharing options...
santaowns Posted July 12, 2009 Author Share Posted July 12, 2009 How do i take the javascript information and parse it through php into mysql tho? I know how to use a database just never used javascript in this fashion. Thanks for the reply Quote Link to comment Share on other sites More sharing options...
.josh Posted July 12, 2009 Share Posted July 12, 2009 You can populate a hidden field in a form and submit it to a php script that inserts it, or use AJAX. Quote Link to comment Share on other sites More sharing options...
santaowns Posted July 12, 2009 Author Share Posted July 12, 2009 did not think of that crayon, thanks Quote Link to comment Share on other sites More sharing options...
santaowns Posted July 12, 2009 Author Share Posted July 12, 2009 Ok i tried a hidden item and i cant seem to get the variable to parse to the results page. Let alone to the database. I am attaching all my code in hopes that you can see my mistakes and help me correct them. header.php <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title><?=$quiz_question?></title> <style type="text/css" media="screen">@import "quiz.css";</style> <style type="text/css"> #time{ font-size:12pt; } </style> <script type="text/javascript"> var digiclock = "00:00:00"; i = 0; function timer() { var digiformat = ""; if(i>3599) { var H = Math.floor(i/3600); } else { var H = 0; } var M = i - (H*3600) if(M>59) { M = Math.floor(M/60) } else { M = 0 } var S = i - (M*60) if(H<10) { H = "0"+H; } if(M<10) { M = "0"+M; } if(S<10) { S = "0"+S; } document.getElementById('time').innerHTML = H+":"+M+":"+S; setTimeout('timer()', 1000); i++; } </script> </head> <body onload="timer()"> <center><img src="images/logo.gif" height=85 width=240></center> <div id="Content"> footer.php </div> <div id="Menu"> <? if($logged_in){ echo 'Logged in as '.$_SESSION['username'].', <a href="logout.php">logout</a>'; }else{ echo 'Not logged in.'; displayLogin(); } ?><br> <a href="#">Pause Training for Patrol</a><br> Time on this module: <div id="time">90</div> </div> </body> </html> login.php <? /** * Checks whether or not the given username is in the * database, if so it checks if the given password is * the same password in the database for that user. * If the user doesn't exist or if the passwords don't * match up, it returns an error code (1 or 2). * On success it returns 0. */ function confirmUser($username, $password){ global $conn; /* Add slashes if necessary (for query) */ if(!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "select password from users where username = '$username'"; $result = mysql_query($q,$conn); if(!$result || (mysql_numrows($result) < 1)){ return 1; //Indicates username failure } /* Retrieve password from result, strip slashes */ $dbarray = mysql_fetch_array($result); $dbarray['password'] = stripslashes($dbarray['password']); $password = stripslashes($password); /* Validate that password is correct */ if($password == $dbarray['password']){ return 0; //Success! Username and password confirmed } else{ return 2; //Indicates password failure } } /** * checkLogin - Checks if the user has already previously * logged in, and a session with the user has already been * established. Also checks to see if user has been remembered. * If so, the database is queried to make sure of the user's * authenticity. Returns true if the user has logged in. */ function checkLogin(){ /* Check if user has been remembered */ if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookpass'])){ $_SESSION['username'] = $_COOKIE['cookname']; $_SESSION['password'] = $_COOKIE['cookpass']; } /* Username and password have been set */ if(isset($_SESSION['username']) && isset($_SESSION['password'])){ /* Confirm that username and password are valid */ if(confirmUser($_SESSION['username'], $_SESSION['password']) != 0){ /* Variables are incorrect, user not logged in */ unset($_SESSION['username']); unset($_SESSION['password']); return false; } return true; } /* User not logged in */ else{ return false; } } /** * Determines whether or not to display the login * form or to show the user that he is logged in * based on if the session variables are set. */ function displayLogin(){ global $logged_in; if($logged_in){ echo "<h1>Logged In!</h1>"; echo "Welcome <b>$_SESSION[username]</b>, you are logged in. <a href=\"logout.php\">Logout</a>"; } else{ ?> <h1>Login</h1> <form action="" method="post"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr> <tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr> <tr><td colspan="2" align="left"><input type="checkbox" name="remember"> <font size="2">Remember me next time</td></tr> <tr><td colspan="2" align="right"><input type="submit" name="sublogin" value="Login"></td></tr> </table> </form> <? } } /** * Checks to see if the user has submitted his * username and password through the login form, * if so, checks authenticity in database and * creates session. */ if(isset($_POST['sublogin'])){ /* Check that all fields were typed in */ if(!$_POST['user'] || !$_POST['pass']){ die('You didn\'t fill in a required field.'); } /* Spruce up username, check length */ $_POST['user'] = trim($_POST['user']); if(strlen($_POST['user']) > 30){ die("Sorry, the username is longer than 30 characters, please shorten it."); } /* Checks that username is in database and password is correct */ $md5pass = md5($_POST['pass']); $result = confirmUser($_POST['user'], $md5pass); /* Check error codes */ if($result == 1){ die('That username doesn\'t exist in our database.'); } else if($result == 2){ die('Incorrect password, please try again.'); } /* Username and password correct, register session variables */ $_POST['user'] = stripslashes($_POST['user']); $_SESSION['username'] = $_POST['user']; $_SESSION['password'] = $md5pass; /** * This is the cool part: the user has requested that we remember that * he's logged in, so we set two cookies. One to hold his username, * and one to hold his md5 encrypted password. We set them both to * expire in 100 days. Now, next time he comes to our site, we will * log him in automatically. */ if(isset($_POST['remember'])){ setcookie("cookname", $_SESSION['username'], time()+60*60*24*100, "/"); setcookie("cookpass", $_SESSION['password'], time()+60*60*24*100, "/"); } /* Quick self-redirect to avoid resending data on refresh */ echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[php_SELF]\">"; return; } /* Sets the value of the logged_in variable, which can be used in your code */ $logged_in = checkLogin(); ?> quiz.php <? /*********************************************************** // With this script you should able to make multiple quizzes // Just call your quiz with its number. // For example: quiz.php?n=1 will include your quiz_1.php // No changes below this unless you REALLY KNOW what you are // doing. /***********************************************************/ session_start(); include("database.php"); include("login.php"); if(!$_GET['n']) exit; require("quiz_".$_GET['n'].".php"); include("header.php"); $timetook = $_POST['timetaken']; if($_GET['action'] == "results") { $choices = $_POST['choices']; $timetook = $_POST['timetaken']; $total_choices = count($choices); if($total_choices == 0) { echo "<div class=\"rings\">Error</div><div class=\"just\">None of the questions is answered! Please <a href=\"javascript:history.back(1)\">go back</a> and answer them!"; } else { if($all_questions_answer && ($total_choices != count($questions_array))) { echo "<div class=\"rings\">Error</div><div class=\"just\">You didn't answer all the questions. Please <a href=\"javascript:history.back(1)\">go back</a> and answer them!"; footer(); include("footer.php"); exit; } /********************* QUIZ RESULT **********************/ if($math_quiz) { // calculate the results // declare an array the same size as choices with only 0 $total_results = count($results_array); for($j=1; $j <= $total_results; $j++) { $int_results_array[$j]=0; } for($i=1; $i <= $total_choices; $i++) { $num = trim($choices[$i]); // if the quiz taker has choosen the correct answer if($num == $correct_result) $int_results_array[$correct_result]=$int_results_array[$correct_result]+1; } $max_value = max($int_results_array); // if max_value is the same as the total number of questoins if($max_value == count($questions_array)) { $right = 1; } if($right) $final_result=$results_array[$correct_result]; else { if($math_quiz_show_correct) { $total = count($questions_array); $final_result = $results_array[$math_quiz_show_correct_before]." <b>$timetook</b> It seems you have gotten <b>$max_value</b> out of $total correct.".$results_array[$math_quiz_show_correct_after]; } else { $final_result=$results_array[$wrong_result]; } } echo $final_result; email_admin($final_result); footer(); include("footer.php"); exit; } /********************* END OF THE QUIZ **********************/ // calculate the results // results array //print_r($results_array); // declare an array the same size as choices with only 0 $total_results = count($results_array); for($j=1; $j <= $total_results; $j++) { $int_results_array[$j]=0; } //print_r($choices); for($i=1; $i <= $total_choices; $i++) { $num = trim($choices[$i]); $int_results_array[$num]=$int_results_array[$num]+1; } //print_r($int_results_array); $max_value = max($int_results_array); $total_int_results_array = count($int_results_array); for($i=1; $i<=$total_int_results_array; $i++) { if($int_results_array[$i] == $max_value) { $max_key = $i; break; } } //echo "the max key is $max_key"; //print_r($int_results_array); //echo "max key is $max_key"; $final_result=$results_array[$max_key]; echo $final_result; } // end of else } // end of the result function function email_admin($final_result) { global $admin_email, $email_notify, $HTTP_USER_AGENT, $REMOTE_ADDR, $HTTP_REFERER, $quiz_question; // email admin if it's enabled if($email_notify) { if($final_result != "") { $final_email_result = str_replace("<div class=\"header\">", "", $final_result); $final_email_result = str_replace("<div class=\"just\">", "", $final_email_result); $final_email_result = str_replace("</div>", "\n\n", $final_email_result); $final_email_result = str_replace("<br />", "\n", $final_email_result); // get the quiz taker's info $date = date("Y-m-d H:i:s"); $ip = $_SERVER['REMOTE_ADDR']; $browser_info = $_SERVER['HTTP_USER_AGENT']; $host = gethostbyaddr($ip); $referer = $_SERVER['HTTP_REFERER']; // from info $from_info = " This is the result of the test taker: $final_email_result ------------------------------------------------------------------------------------------ IP: $ip HOST: $host Browser: $browser_info Time: $date Referred by: $referer ------------------------------------------------------------------------------------------"; $subject = "Someone has taken $quiz_question quiz"; //echo "in footer, trying to send mail: $admin_email, $final_result, $from_info, $subject"; mail($admin_email, $subject, $from_info, "From: Test_Taker"); } // end of if final result is not empty } // end of if } function footer() { } // end of footer function if(!$_GET['action']) { echo "<div class=\"header\">".$quiz_question."</div>\n<div class=\"just\">".$quiz_description."</div>"; echo "<form action=\"quiz.php?n=".$_GET['n']."&action=results\" method=\"post\" onsubmit=\"change()\">"; for($i = 1; $i <= count($questions_array); $i++) { echo "<div class=\"rings\">".$questions_array[$i]."</div>\n"; // find the answers $this_answers = explode("\n", $answers_array[$i]); // print the answers and modify the results echo "<div class=\"just\">\n"; for($k = 0; $k < count($this_answers); $k++) { $this_particular_answer = explode("|", $this_answers[$k]); echo "<label><input type=\"radio\" name=\"choices[".$i."]\" value=\"".trim($this_particular_answer[1])."\">".$this_particular_answer[0]."</label><br /> \n"; } echo "<input type=\"hidden\" id=\"timetaken\" name=\"timetaken\" />"; echo "</div><br />\n"; //print_r($this_answers); } // end of for echo "<input type=\"submit\" value=\"".$submit_button."\" class=\"form\"></form>"; } // end of if not action footer(); email_admin($final_result); include("footer.php"); ?> quiz_1.php <?php // Would you like to get get an email when someone takes this particular quiz? $email_notify = 0; // 1 = yes 0 = no // if so $admin_email = "you@domain.com"; $timetook = $_POST['timetaken']; // Your quiz question: $quiz_question = "Module Name"; // What you want your submit button to say? $submit_button = "Submit"; // Your quiz description: $quiz_description = "Just a simple test quiz to show you how it works and what it can do. In order to get 100%, you must answer all the following correctly. are we able to use html? <br /><br />yes if two lines down. How far can this be? lets try 25 spaces down. <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />15 spaces down hows it look?<br /><br /><ul /><h1 />Take the module Test</h1 /></ul />"; // Do you want to make sure that all of your questions are answered before the results are calculated? $all_questions_answer = 1; // 1 = yes 0 = no // Is this a math quiz? $math_quiz = 1; // 1 = yes 0 = no /********************************************** The following variables are for math quiz only means please ignore them if you are not making a MATH QUIZ! ***********************************************/ // If this is a math quiz, the correct result is no: $correct_result = 2; // If this is a math quiz, the wrong result is no: $wrong_result = 1; // If this is a math quiz, will you like the script to show the quiz taker how many of the questions they got right? $math_quiz_show_correct = 1; // 1 = yes 0 = no /********************************************** the following variables are for if you want the script to show the number of correct numbers only! means ignore if you don't want the script to do so. ***********************************************/ // if you want the scrpit to show the number of correct answers. // you want to provide the result displayed before the number of corrects: $math_quiz_show_correct_before = 3; // see the example // and after the number of correct answers: $math_quiz_show_correct_after = 4; // see the example /********************************************** end of ignore ***********************************************/ /********************************************** END OF IGNORE ***********************************************/ // Now for each result, give it a description. Please make sure you put \ in front your quotations or you will get parse error! // WARNING: if this is a math question, please leave the variable "$adding" in the WRONG result in order for the script to show how many questions the quiz taker has gotten correct. $results_array = array( 1 => "<div class=\"header\">Oops</div><div class=\"just\">You didn't get them all correct.<br /><br /> Add more your description here. blah blab blah blah blab blah blah blab blah blah blab blah blah blab blah blah blab blah blah blab blah blah blab blah blah blab blah blah blab blah blah blab blah </div>", 2 => "<div class=\"header\">100%</div><div class=\"just\">$timetook WOW, amazing you got all of the questions correct.<br /><br /><a href=\"quiz.php?n=2\">Continue to next module</a> </div>", 3 => "<div class=\"header\">Please Try Again</div><div class=\"just\">You didn't get them all correct. <a href=\"quiz.php?n=101\">click here to take the test again.</a> ", 4 => "", ); // Now your questions $questions_array = array( 1=> "1 + 2 =", 2=> "30 x 60 =", 3=> "300 / 50 =", ); // your answers. MAKE SURE it's the same order as the questions. also gives which of the results is the answer corresponding to separated by the symbol |. One unique answer per line! $answers_array = array( 1=> "1|1 2|1 3|2 4|1", 2=> "18|1 180|1 1800|2 18000|1", 3=> "60|2 6|1 600|1 6000|1", /******************************************* I hope you get the idea now. Just add more if you have more questions. Make sure to change the index numbers. For example, the next one should begin with 3=> "blah|1 blah|2 blah|3", always end with a quotation and a comma! *******************************************/ ); ######### END OF QUIZ 1 DATA ################################################## ?> database.php <?php $db_user = "username(this isnt what mine has)"; $db_password = "password(this isnt what mine has)"; $database = "database(this isnt what mine has)"; $server = "localhost"; $conn = mysql_connect($server, $db_user, $db_password) or die(mysql_error()); mysql_select_db($database, $conn) or die(mysql_error()); ?> Quote Link to comment Share on other sites More sharing options...
santaowns Posted July 14, 2009 Author Share Posted July 14, 2009 fixed had to recode whole thing. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.