I am coding an online quizzer using PHP. Whenever the answerer of the quiz choose the correct answer, the code will automatically +1 to his overall score.
To do that, I used $_SESSION['score']=0; to first set the score to zero and $_SESSION['score']++; whenever the answerer gets the answer correct for each question.
However, I have no idea why the score is not adding up despite the answerers answering the questions correctly.
When the answerer answers the question correctly, the score is still 0 for some reason and I have no idea why. May I know what went wrong? Thank you.
Things I have tried:
1.Changing $_SESSION['score']++; to $_SESSION['score']+1;
2.Changing:
if(!isset($_SESSION['score'])){
$_SESSION['score']=0;
}
to just
$_SESSION['score']=0;
3.Changing
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}
to just:
if($correct_choice = $selected_choice){
$_SESSION['score']++;
}
Below is the code for process.php:
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
if(!isset($_SESSION['score'])){
$_SESSION['score']=0;
}
if(isset($_POST['submit'])){
$number=$_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
/*
* Get total questions
*/
$query="SELECT* FROM questions";
$results= mysqli_query($con,$query);
$total=$results->num_rows;
/*
* Get correct choice
*/
$query = "SELECT* FROM `choices` WHERE question_number = $number AND is_correct=1";
//Get result
$results= mysqli_query($con,$query);
//Get row
$row=$results->fetch_assoc();
//Set Correct choices
$correct_choice=$row['id'];
//Compare choice made with correct choice
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}
//Check if last question
if($number == $total){
header("Location: final.php");
exit();
} else {
header("Location: question.php?n=".$next);
}
}
Just tried something:
if($correct_choice == $selected_choice){
echo "same";
} else{
echo "not same";
}
Even though $correct_choice and $selected_choice are both equals to 1, the code still returns as "not same"?
You are opening and closing a lot of PHP tags - unnecessarily. If you have error reporting on, and being displayed on screen, it would likely be saying 'headers already sent'. That, is likely the issue.
Since the process.php file is all php - just open the <?php tag once - and don't even bother to close it at the end - unless you are explicitly outputting something (which is bad practice anyway for a larger program, better to use a small framework, and separate templates).
Make sure that your code does not output anything to the browser before session_start() is called.
you can find more information about $_SESSION superglobal here.
To use cookie-based sessions, session_start() must be called before
outputing anything to the browser.
Related
UPDATE - I finally figured this out, and I've added the answer below :-) (I'll accept it as answered as soon as the system allows me to)
I think that I'm probably doing something very simple incorrectly (i.e. calling the variable incorrectly), as I've had similar issues in several situations.
I am creating a password reset form and would like to include the various steps and form sections on one page. I'm doing this using a series of elseif statements to determine which html code to display and/or php script to execute, and changing the value of the variable as a series of queries succeed or fail.
I've tested the queries and the var value changes correctly (I've echo'd the value at each step to confirm that) but the correct result isn't being displayed unless the var value is set manually.
For purposes of the question I've included 2 simplified snippets - a very basic scenario (which I can easily apply to my code), and a simplified version of my code, and I'd be happy to share the full code if that's preferable.
EDIT - I've also tried calling GLOBAL $status; before setting a new value for $status, on the off-chance that was the problem.
Basic Scenario:
<?php
//session_start and connect to database
$status="start";
?>
<?php $status="start"; ?>
<?php if ($status == "start") { ?>
Check if expiry valid & retrieve info
<?php $status = "expiry_ok"; ?>
<?php }
elseif ($status == "expiry_ok")
{ ?>
Date is Valid
<?php } ?>
Simplified Version of Query:
<?php if ($status == "start"){
//Identify the $temp_password by removing the URL
$restorepasslink="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$new_pass = str_replace("http://click2fit.com/demo/restorepass.php/", "", $restorepasslink);
//Query db to check if expiry_date has passed
$qry="SELECT * FROM password_reset WHERE temp_password = '$new_pass'";
$result=mysql_query($qry);
if($result) {
$token = mysql_fetch_assoc($result);
$token_expiry_date = $token['expiry_date'];
// Other $token values are also set here
if($date < $token_expiry_date) {
$status = "expiry_ok";
}else {
$status = "expiry_notok";
}
}
?>
Note: Since most of the tutorial are still written for mysql queries instead of PDO, I'm first trying to get it all to work that way before switching it over to PDO.
I solved the problem by removing the initial if statement:
if ($status == "start"){...}
and simply starting the elseif statements with
if ($status == "expiry_ok"){...}
elseif (...)
I also removed the initial declaration of the $status="start";
if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.
Annoyingly my log in check script is not redirecting where I tell it to.
I know it hits the if statements correctly because I put in echos to check it did.
It is blatantly skipping to header as during the first circumstance it echos "- blanks" as it should then also "Did it even get this far?"
So on that basis I know it hits the header - its just plain ignoring it and I can not for the life of me fathom why.
Im sure its simple and I'm missing something ridiculously obvious but I just cant see it.
Any suggestions?
// makes sure they filled it in
if($_POST['frmLogin-username'] == "" || $_POST['frmLogin-password'] == ""){
echo " - blanks";
header('Location: ?page=landing&action=login&message=1');
echo "Did it even get this far?";
die;
}
else{
// checks it against the database
$query = mysql_query("SELECT * FROM shops WHERE shopUsername = '".$_POST['frmLogin-username']."'");
//Gives error if user dosen't exist
$count = mysql_num_rows($query);
if ($count == "0"){
echo " - no user";
header('Location: ?page=landing&action=login&message=2');
die;
}
else{
while($row = mysql_fetch_array( $query )){
//gives error if the password is wrong
if ($_POST['frmLogin-password'] != $row['shopPassword']){
echo " - wrong pass";
header('Location: ?page=landing&action=login&message=3');
die;
}
else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie(shopusername, $_POST['frmLogin-username'], $hour);
setcookie(shopid, $row['shopId'], $hour);
//then redirect them to the shop panel
header("Location: ?page=shop");
die;
}
}
}
}
EDIT: The issue was to do with the way I load all my pages within index.php by calling includes which I am now investigating
I have moves this process page to its own php file and it now works fine
First of all: you can not send headers after having output anything using echo like Sam said in his comment.
Secondly, to send a redirect, the URL after the Location: must be absolute, like http://localhost/page/to/redirect/to.php.
EDIT
Corbin actually beat me to my answer for about 10 seconds ;-)
The issue was to do with the way I load all my pages within index.php by calling includes which I am now investigating I have moved this process page to its own php file and it now works fine
You can use window.location, just echo it within PHP.
I'm having problem with this code and I can't figure out where the problem is. So when I run this code: if $row["count"] > 0 the else block is run and $_SESSION["error"] is set.
When $row["count"] == 0 query is executed and new row is inserted into database but both $_SESSION["save"] and $_SESSION["error"] are set! Does this mean that both if and else statements are run? It doesn't make any sense to me...
$stmt = $pdo->prepare("SELECT COUNT(*) AS count ... QUERY");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( $row["count"] == 0 ){
$stmt = $pdo->prepare("INSERT...QUERY");
$stmt->execute();
$_SESSION["save"] = "Saved";
header("Location:index.php");
exit();
}else{
$_SESSION["error"] = "Error";
header("Location:index.php");
exit();
}
i'm using this code in index.php
$save = (isset($_SESSION["save"]))? $_SESSION["save"] : false;
$error = (isset($_SESSION["error"]))? $_SESSION["error"] : false;
unset($_SESSION["error"]);
unset($_SESSION["save"]);
As I said, when $row["count"] == 0 I have both $save and $error set..
SOLVED
It appears that I found the problem. I've changed they way I access the script from:
<a href='script.php?id=10'><input type="button" value='Go to script' /></a>
to:
<a href='script.php?id=10'>Go to script</a>
And the script is working now. With the input button tag inside the a tag the script was behaving unpredictable executing the if and else statement in the same time.. I'm still confused why and how input tag caused that, but at least the script is working now...
Are you clearing $_SESSION["error"] and $_SESSION["save"] after they have been read in index.php? It sounds to me like you have run across both cases once and have lingering values in your $_SESSION array.
I suggest using the same variable name for both cases, e.g. $_SESSION['save'], and assigning either success or error to it. That way, you don't have to check whether one of two variables exist, but only what its contents are.
And don't forget to clear or unset the variable after it has served its purpose.
FOr example, when you trying this, if in a stage $row["count"] > 0 session will record $_SESSION["error"] . It will be stored if you don't delete it. Because of this $_SESSION["error"] is setted.
Maybe you have executed your code twice and ["error"] was still set. You dont clear it on success.
According to your logic, it is impossible for both conditions to run at the same time. However, I'm sure you've run this script multiple times. Sometimes with IF, sometimes with ELSE. It doesn't seem like you're ever clearing the $_SESSION variables.
Solution:
Right after you use the $_SESSION['save'] or $_SESSION['error'] variables, unset them.
unset($_SESSION['save']);
or
unset($_SESSION['error]');
I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php