Mysql save PHP variables to table - php

I have a very specific problem
I want to save / load two variables to database, and the third variable use as identificator
My current -not working- code:
$sql = mysql_query("INSERT INTO time (meno, minuty, sekundy) VALUES('$firstName','$minutes','$seconds')");
if (mysql_error()) die('Error, insert query failed');
What I want in the nutshell: When I log with name (etc Roman[$firstName variable]), it will load a previous $minutes and $seconds numbers, and save every (etc minute) new one (it is a timer, so save a time)
I hope you understand
Thanks for your time, I aprreciade it
My current timer.php
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=Windows-1250" />
<title>Timing Stránka</title>
<script>
let startTime, endTime;
$(window).on('load', () => {
startTime = new Date();
});
function time_elapsed() {
endTime = new Date();
let timeDiff = endTime - startTime;
let timeSpent = timeConversion(timeDiff);
const formData = new FormData();
formData.append('timeSpent', timeSpent);
/* The line below is used to send data to the server-side. This way is reliable than using AJAX to send the data especially in cases when you are listening for an unload event. You can read more about navigator.sendBeacon() in MDN's site. */
navigator.sendBeacon('db.php', formData);
}
function timeConversion(time) {
let seconds = (time / 1000).toFixed(1);
let minutes = (time / (1000 * 60)).toFixed(1);
let hours = (time / (1000 * 60 * 60)).toFixed(1);
let days = (time / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) {
return seconds + " second(s)";
} else if (minutes < 60) {
return minutes + " minute(s)";
} else if (hours < 24) {
return hours + " hour(s)";
} else {
return days + " day(s)";
}
}
/* Note: In the line below, i listen to the unload event, you can change this event to a button click or anything else you want to listen to before calling the function. This is better than calling setInterval() every second and i think it will help your application performance also. */
window.addEventListener('beforeunload', time_elapsed, false);
</script>
</head>
<body>
</div>
</br>
</br>
</br>
<?php
echo $timeSpent
?>
And the db.php:
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
// DB connection
$host = 'db.mysql-01.gsp-europe.net';
$db_name = 'xxxx';
$username = 'xxx';
$password = 'xxxx';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection Error: " . $e->getMessage();
}
if (isset($_POST['timeSpent'])){
$timeSpent = $_POST['timeSpent'];
// create query
$query = 'INSERT INTO user_time SET time = :time';
// prepare statement
$stmt = $conn->prepare($query);
// bind data
$stmt->bindParam(':time', $timeSpent);
// execute query and check if it failed or not
if ($stmt->execute()){
echo "Query Successful";
} else {
printf("Error: %s.\n", $stmt->error);
}
}
?>

Please create two tables one table for saving two variables and another table to saving identificator. Then use foreign key and relationships with JOINS. Hope these steps will save your problem.

Kindly replace the code in your "time.php" with this:
<?php
header('Content-Type: text/html; charset=Windows-1250');
session_start();
$firstName = $_SESSION['firstname'];
$minutes = $_POST['minutes'];
$seconds = $_POST['seconds'];
// DB connection
$host = 'localhost';
$db_name = 'zadmin';
$username = 'xxx';
$password = 'zadmin_nahovno';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection Error: " . $e->getMessage();
}
// create query
$query = 'INSERT INTO time SET meno = :firstName, minuty = :minutes, sekundy = :seconds';
// prepare statement
$stmt = $conn->prepare($query);
// bind data
$stmt->bindParam(':firstName', $firstName);
$stmt->bindParam(':minutes', $minutes);
$stmt->bindParam(':seconds', $seconds);
// execute query and check if it failed or not
if ($stmt->execute()){
echo "Query Successful";
} else {
printf("Error: %s.\n", $stmt->error);
}
?>
/*
This should work (if not, then something is wrong with your variables, you should look into your variables and see if they are actually holding any data). You can make use of var_dump() to examine the variables.
*/
Meno Užívateľa: <b> <?php echo $firstName; ?> </b>
</br>
</br>
Momentálne majníš : <b> <?php echo $minutes; ?> Minút </b> <b> a </b> <b> <?php echo $seconds; ?> Sekúnd </b>
</br>
</br>

#Hnusny Pleb, so in order to get the amount of time spent on a page, i wrote the following code for you.
First, in your script, you should write this:
<script>
let startTime, endTime;
$(window).on('load', () => {
startTime = new Date();
});
function time_elapsed() {
endTime = new Date();
let timeDiff = endTime - startTime;
let timeSpent = timeConversion(timeDiff);
const formData = new FormData();
formData.append('timeSpent', timeSpent);
/* The line below is used to send data to the server-side. This way is reliable than using AJAX to send the data especially in cases when you are listening for an unload event. You can read more about navigator.sendBeacon() in MDN's site. */
navigator.sendBeacon('index.php', formData);
}
function timeConversion(time) {
let seconds = (time / 1000).toFixed(1);
let minutes = (time / (1000 * 60)).toFixed(1);
let hours = (time / (1000 * 60 * 60)).toFixed(1);
let days = (time / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) {
return seconds + " second(s)";
} else if (minutes < 60) {
return minutes + " minute(s)";
} else if (hours < 24) {
return hours + " hour(s)";
} else {
return days + " day(s)";
}
}
/* Note: In the line below, i listen to the unload event, you can change this event to a button click or anything else you want to listen to before calling the function. This is better than calling setInterval() every second and i think it will help your application performance also. */
window.addEventListener('beforeunload', time_elapsed, false);
</script>
After writing the script above, the data will be sent to your server-side and then you can simply store the time spent (i.e. in seconds, minutes, hours or days) into your DB. In order to do that, you should write something similar to this in your server-side:
<?php
if (isset($_POST['timeSpent'])){
$timeSpent = $_POST['timeSpent'];
// create query
$query = 'INSERT INTO user_time SET time = :time';
// prepare statement
$stmt = $conn->prepare($query);
// bind data
$stmt->bindParam(':time', $timeSpent);
// execute query and check if it failed or not
if ($stmt->execute()){
echo "Query Successful";
} else {
printf("Error: %s.\n", $stmt->error);
}
}
?>
Kindly find a way to use the written code to achieve your goals. I think ive tried my best in helping you. Good Luck.

Okey, i Got it.. Here is a code:
Timing PAGE:
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
session_start();
$_SESSION['firstname'] = $firstName;
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=Windows-1250" />
<title>Timing Stránka</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('db.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>
</head>
<body>
</div>
</br>
</br>
</br>
<div id="load_tweets"> </div>
Time on page: <label id="minutes">00</label>
<label id="colon">:</label>
<label id="seconds">00</label>
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<INPUT TYPE="button" onClick="history.go(0)" VALUE="Oprava">
</body>
</html>
The page of timing AKA db.php:
<?php
header('Content-Type: text/html; charset=Windows-1250');
session_start();
$firstName = $_SESSION['firstname'];
$_SESSION['firstname'] = $firstName;
$servername = "db.xxxx.gsp-europe.net";
$username = "xxxxxx";
$password = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
$dbname = "xxxxx";
/// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$stmt = $conn->prepare("SELECT points FROM member_profile WHERE user_id = '$firstName'");
$stmt->execute();
$array = [];
$resalts = $stmt->get_result();
while ($row = $resalts->fetch_array(MYSQLI_ASSOC))
{
$points = $row['points'];
}
$hours = floor($points / 3600);
$mins = floor($points / 60 % 60);
$secs = floor($points % 60);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// check if the user exist
$check = "SELECT * FROM `member_profile` WHERE user_id = '$firstName'";
$result = mysqli_query($conn,$check) or die(mysqli_error($conn));
$rows = mysqli_num_rows($result);
//if exist increse points with 1
if($rows>=1){
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
}
//if don't exist create user with points 0
if($rows==0)
{
$query = "INSERT into `member_profile` (user_id, points) VALUES ( '$firstName' ,'0')";
$result = mysqli_query($conn,$query)or die(mysqli_error($conn));
$conn->close();
}
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=Windows-1250" />
</head>
<body>
</div>
</br>
Meno Užívateľa: <b> <?php echo $firstName; ?> </b>
</br>
</br>
Overall time : <b> <?php echo $timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs); ?> </b>
</body>
</html>

Related

Ajax code with error that I cannot locate

I have a Ajax code snippet that has a bug that I cannot find.
The code worked a while back perfectly but now I cannot locate it, all seems to be correct.
I have tried to check my db codes, all good.
Tried to eliminate excessive code to bring it to basics, no result.
I have a text line that say "there are reviews" yet they are not shown. I have no MariaDB errors visible.
pagination_parser.php in directory 'includes'
<?php
// Make the script run only if there is a page number posted to this script
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9]#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9]#', '', $_POST['last']);
$pn = preg_replace('#[^0-9]#', '', $_POST['pn']);
// This makes sure the page number isn't below 1, or more than our $last page
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last) {
$pn = $last;
}
// Connect to our database here
require("db_connect.inc.php");
// This sets the range of rows to query for the chosen $pn
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "SELECT * FROM reviews WHERE status='1' ORDER BY reg_date DESC $limit";
$query = mysqli_query($db_conx, $sql);
$dataString = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$stars = $row["stars"];
$comment = $row["review"];
$itemdate = strftime("%b %d, %Y", strtotime($row["reg_date"]));
$dataString .= $stars.'|'.$comment.'|'.$itemdate.'||';
}
// Close your database connection
mysqli_close($db_conx);
// Echo the results back to Ajax
return $dataString;
exit();
}
?>
index.php in folder 'texts'
<?php
// Connect to our database here
require "../includes/db_connect.inc.php";
// Create connection
$db_conx = new mysqli($host, $user, $password, $database);
// Check connection
if ($db_conx->connect_error) {
die("Connection failed: " . $db_conx->connect_error);
}
// This first query is just to get the total count of rows
$sql = "SELECT COUNT(id) FROM review WHERE status='1'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
// Here we have the total row count
$total_rows = $row[0];
// Specify how many results per page
$rpp = 5;
// This tells us the page number of our last page
$last = ceil($total_rows/$rpp);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Close the database connection
mysqli_close($db_conx);
?>
<!DOCTYPE html>
<html>
<head>
<script>
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
function request_page(pn){
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
var hr = new XMLHttpRequest();
hr.open("POST", "pagination_parser.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "stars: "+itemArray[0]+" - date "+itemArray[2]+" - comment <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
// Change the pagination controls
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
</head>
<body>
<div id="pagination_controls"></div>
<div id="results_box"></div>
<script> request_page(1); </script>
</body>
</html>
I do expect to have the html table with data, but just get the "loading results ..." .. but no data.
And mysql user and settings are checked, mysql direct query works fine, but I just don't get it on my development site.
I use development subsection to find bugs, but here I am about to give in.
My Ajax knowledge is just not good enough. Oh, it's not real ajax but XMLHttpRequest code.
Wouldn't mind to update to proper Ajax.
Looks like a simple mistake to me:
// Echo the results back to Ajax
return $dataString;
return will not echo your result like the comment says. Use one of the following:
echo construct:
echo $dataString;
exit();
print construct
print $dataString;
exit();
die function:
die($dataString);
exit function:
exit($dataString);

how to insert date using php into mysql query? [duplicate]

This question already has answers here:
Using Mysqli bind_param with date and time columns?
(5 answers)
Closed 1 year ago.
what i'm trying to do is get date from html input, execute a query using that date. but i can't seem to figure out what is the problem, i'm doing everything right (or am i?)
Here is some code index.php
<head>
<script>
function showReport(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("report").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/reports.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
Select Date: <input type="date" onchange="showReport(this.value)">
</form>
<p>Results: <span id="report"></span></p>
</body>
</html>
here is the ajax handler reports.php
// get the q parameter from URL
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chaska";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$input_date=$_REQUEST['q'];
$date=date("Y-m-d",strtotime($input_date));
$sql = "SELECT `tec_sale_items`.product_name, `tec_sales`.date, sum(`tec_sale_items`.quantity) AS sum FROM `tec_sale_items` LEFT JOIN `tec_sales` ON `tec_sale_items`.sale_id = `tec_sales`.id WHERE DATE(`tec_sales`.date) = $date AS DATE group by `tec_sale_items`.product_name, DATE(`tec_sales`.date)";
$result = $conn->query($sql);
echo $date;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "product: " . $row["product_name"]. " - Quantity: " . $row["sum"]. " ". "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The query returns nothing. When I replace $date AS DATE by CURRENT_DATEthe query executes fine but I want a specific date to work as well
The following is illegal SQL syntax for two reasons; it's missing quotes around the $date variable (which is a string), and you try to give it an alias (all you're doing is comparing two values, so aliasing makes little sense here).
WHERE DATE(`tec_sales`.date) = $date AS DATE
You should also be using a prepared statement with MySQLi, as shown below. Using a prepared statement means that you no longer need to worry about quoting your variables.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chaska";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$input_date = $_REQUEST['q'];
$date = date("Y-m-d",strtotime($input_date));
$sql = "SELECT `tec_sale_items`.product_name,
`tec_sales`.date,
sum(`tec_sale_items`.quantity) AS sum
FROM `tec_sale_items`
LEFT JOIN `tec_sales`
ON `tec_sale_items`.sale_id = `tec_sales`.id
WHERE DATE(`tec_sales`.date) = ?
GROUP BY `tec_sale_items`.product_name, DATE(`tec_sales`.date)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $date);
$stmt->execute();
$stmt->bind_result($product_name, $date, $sum);
if ($stmt->fetch()) {
do {
echo "product: ".$product_name. " - Quantity: " . $sum. " <br>";
} while ($stmt->fetch());
} else {
echo "0 results";
}
$stmt->close();
WHERE DATE(`tec_sales`.date) = $date
Use single quotes around date value, otherwise it is evaluated as arithmetic operation - 2019-07-23 = 2012 - 23 = 1989.
Correct condition:
WHERE DATE(`tec_sales`.date) = '$date'
There is no risk of sql injection, because input value is parsed by strtotime.
what you did is right
Select Date: <input type="text" onchange="showReport(this.value)" >
but use text instead of date

How to restrict access to page with php

I can't seem to find a way to block my page from being accessed. I have a page to give tickets to users in mysql, but you can simply type it into http to receive tickets, how do i stop people from doing that??
<html>
<head>
<?php
header("refresh:33;url=tickets_give.php" );
?>
<link rel="stylesheet" href="finessecss.css">
</head>
<body bgcolor="#F9F9F9" background="background3.jpg">
<div class="videobox">
<div class="video"><p>Video Player Unavailable At This Moment</p></div>
<div class="clockbox">
<span id="countdown" class="timer"></span>
<script>
var seconds = 30;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown')[0].innerHTML = "";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
</div>
</div>
</body>
</html>
There is my code for my video page
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "users_database";
session_start();
$name = $_SESSION['name'];
$pass = $_SESSION['pass'];
if (!(isset($_SESSION['can_accesss']) && $_SESSION['name'] != '')) {
Header("Location:welcome_get.php");
}
unset($_SESSION['can_access']);
// rest of page code
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ('$access' == 'Finesseshopisthebest'){
;
}
else{
echo'mysql' or die;
}
$sql = "UPDATE users_database SET tickets=tickets+10 WHERE username= '$name' and password= '$pass'";
if (mysqli_query($conn, $sql)) {
Header("Location:tickets.php");
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
</body>
</html>
And that is my give tickets page. How do i stop people from going straight to tickets_give.php?
If you're looking for a 20-second solution, just check for the presence of a precise query string, eg yoursite.com/somepage?foo=bar. If $_GET["foo"] is not set, call exit and forget about it.
Warning: this is security through obscurity; anyone with a network monitor or even just shoulder surfing would breeze past this, but I guess it's better than nothing. Clearly a smarter, long-term solution is to add meaningful authentication, but it sounds like you have a very short-term problem you need to solve!

Php code does not send query to database

I am trying to update my database using ajax, but I cannot seem to understand why the php code does not update the database. The script:
function Insert () {
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST","list_insert.php");
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
var returnedData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('messageDiv');
messageDiv.innerHTML = returnedData;
}
}
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
var data = item + '|' + desc + '|';
XMLHttpRequestObject.send("data=" + data);
}
return false;
}
This is the php code for list_insert:
<?php
include "function_list.php";
$myData = $_POST['data'];
$datetime = date('Y-m-d H:i:s');
list($items,$description) = explode ('|',$myData);
$statement = "INSERT INTO record ";
$statement .= "(items,description) ";
$statement .= "VALUES (";
$statement .= "'".$items."', '".$description."')";
print $statement;
insert($statement);
print "done";
?>
My php function to insert into the db (function_list):
<?php
$con=mysqli_connect("localhost","shop");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function insert($statement) {
global $con;
mysqli_query($con,$statement);
}
?>
When I print the statement out, the query is correct (I have verified this by manually copy pasting it in mysql). I think the issue is with my insert function.
Any help is appreciated,
thank you.
Firstly, all mysql statements must end in a semicolon.
Secondly, have you made sure $items and $description are the values you expect them to have? Do they have any unescaped quotes?
Also, typically you would send each of the fields as a separate value like so:
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
XMLHttpRequestObject.send("items=" + item + "&desc=" + desc);
$$items = $_POST['items'];
$description = $_POST['desc'];
By default, the username for mysql is root, and the password is blank, even though you aren't prompted for these, they are set by default.
I think this might be the issue
in ur global variable $con letz say you put this
$con = new mysqli("host", "user", "pwd", "dbname");
then
function insert($statement) {
$con->query($statement);
$con->close();
}

Undefined Index .. But I have done the same thing in short..then running

I am making online examination.. the data are passing from page to examination page. but the value of radio button is not passing from examination page to result page. I have checked that the course name and subject names are passing. I have added the timer section. Which is working good. The value of radio button inside the while is not passing to result..
EXAM CODE
<html>
<head>
<title>EXAM</title>
</head>
<body>
<?PHP
//$i=1;
$j=1;
$user_name = "root";
$password = "";
$database = "online_exam";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
if ($db_found)
{ session_start();
$i=$_SESSION['$i'];
$sub = $_SESSION['$sub'];
/*if(isset($_POST['b_subject']))
{
$selected_button=$_POST['subject'];
if($selected_button=='subject1')
$_SESSION['$sub']= "GK";
else if($selected_button=='subject2')
$_SESSION['$sub']="math";
else
print "error";
}*/
if(isset($_POST['subject'])){
$selected_button=$_POST['subject'];
}
else
{
$selected_button="default button";
}
while($j<$i)
{
if($selected_button=='subject'.$j)
$s= $sub[$j];
$j++;
}
//print $_SESSION['$sub'];
//print $selected_button;
//print $_SESSION['$cour'];
//print
// //assign $_SESSION['array'] to $array
//print $sub[1];
/* foreach($sub as $value) {
print $value; //print $array contents
}*/
$c = $_SESSION['$cour'];
//$s = $_SESSION['$sub'];
$SQL = "SELECT ques FROM ques_ans WHERE course='$c' AND subj='$s'";
$result = mysql_query($SQL);
echo '<FORM name ="form1" method ="post" action="result_a.php" >';
while ( $db_field = mysql_fetch_assoc($result) )
{
print $db_field['ques']."<BR>";
?>
<Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '1'>YES
<Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '0'>NO
<br>
<?PHP
$i++;
}
$_SESSION['$i']= $i;
//$_SESSION['ques'] = $que;
$_SESSION['$sub'] = $s;
echo '<input type="submit" name="submit" id="submit" value="SUBMIT"/></FORM>';
mysql_close($db_handle);
}
$targetDate = time()+(330*60) + (1*30);
$actualDate = time()+(330*60);
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
?>
<h1>Time Left</h1>
<script type="text/javascript">
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown ()
{
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
document.getElementById("remain").innerHTML = hours+" hours : "+minutes+" minutes : "+seconds+" seconds";
SD=window.setTimeout( "setCountDown()", 1000 );
if (minutes == '00' && seconds == '00') { seconds = "00"; window.clearTimeout(SD);
window.alert("Time is up. Press OK to continue.");
window.location = "http://localhost/result_a.php"
}
}
</script>
<body onload="setCountDown();">
<div id="remain"><?php echo "$remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds";?></div>
</body>
</html>
Inside the result the line " $selected_radio = $_POST['ques'.$i];" is showing error that "Undefined index: ques1" , "Undefined index: ques2", ... so on....
RESULT CODE
<html>
<head>
<title>RESULT</title>
<body>
<?PHP
$i=1;
$count=0;
$ans= "";
session_start();
//$i=$_SESSION['$i'];
$s=$_SESSION['$sub'];
$c=$_SESSION['$cour'];
//$que[]=$_SESSION['ques'];
//print $c.$s;
$user_name = "root";
$password = "";
$database = "online_exam";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database,$db_handle);
$SQL = "SELECT ans FROM ques_ans WHERE course='$c' AND subj='$s'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) )
{
$selected_radio = $_POST['ques'.$i];
if ($selected_radio == '1')
{
$ans='1';
}
else if ($selected_radio == '0')
{
$ans='0';
}
if($ans==$db_field['ans'])
$count++;
$i++;
}
print $count;
?>
</body>
</html>
</head>
you never define $i = anything before you attempt to perform $i++;, you cannot autoincrement an integer without declaring it's starting value.
Therefore your fields are all actually just
name="ques"
Without any integer appended to them. Define $i = 1; or $i = 0; depending on your desire, and this will be resolved.

Categories