I've a fb quiz application which is working fine if we check correct question and then go for next question but its showing negative score when i change options multiple times
I'm calling ajax onchange on selecting option to update score page and storing score in session
in this codes it works fine if we select correct answer and then wrong so it decrease but when selecting wrong and then we got negative score because of
$_SESSION['score']--;
How to solve this problem ???
// check if this option is correct for current question
$check_anwer_query = mysql_query("select * from tbl_option where ques_id=$ques_id and opt_id=$opt_id") or die(mysql_error());
if(mysql_num_rows($check_anwer_query))
{
$rs = mysql_fetch_array($check_anwer_query);
if($rs['opt_value']==1)
{
$_SESSION['score']++;
//$_SESSION[$ques_id]='1';
}
else if($_SESSION['lastq']==$ques_id) // check if option is changed,
{
$_SESSION['score']--;
}
if(isset($_SESSION['user']))
{
mysql_query("delete from tmp_quiz where ques_id=$ques_id and uid='".$_SESSION['user']."'") or die(mysql_error());
if($rs['opt_value']==1)
{
mysql_query("insert into tmp_quiz(ques_id,opt_id,uid,is_correct) values($ques_id,$opt_id,'".$_SESSION['user']."',1)") or die(mysql_error());
}
else
{
mysql_query("insert into tmp_quiz(ques_id,opt_id,uid,is_correct) values($ques_id,$opt_id,'".$_SESSION['user']."',0)") or die(mysql_error());
}
}
else
{
mysql_query("delete from tmp_quiz where ques_id=$ques_id and tmp_id='".$_SESSION['tmp_id']."'") or die(mysql_error());
mysql_query("insert into tmp_quiz(ques_id,opt_id,tmp_id) values($ques_id,$opt_id,'".$_SESSION['tmp_id']."')") or die(mysql_error());
}
}
$_SESSION['lastq'] = $ques_id; // assign current question as last question answred
?>
//Logic for Score Start
$rs = mysql_fetch_array($check_anwer_query);
if($rs['opt_value']==1)
{
$_SESSION['score']++;
$_SESSION["test_".$ques_id]='1'; // if Answer is Correct Set Session
}
elseif($_SESSION['lastq']==$ques_id) // check if option is changed
{
if(isset($_SESSION["test_".$ques_id])) { // if Last Ansewer is same as current question and last answer is yes then substract score
$_SESSION['score']--;
unset($_SESSION["test_".$ques_id]); } // Unset That Session
}
elseif(isset($_SESSION['test_'.$_SESSION['lastq']])) // If Last Question Session is still exists Then Unset That Question Session
{
unset($_SESSION['test_'.$_SESSION['lastq']]);
}
//Logic for Score End
You should not do relative calculations, since that requires you to be certain that the state shared between the UI and your session is 100% in sync and that no user actions arrive out of order (which I guess is where your problem is).
Instead, save all chosen answers in the session. When wanting to display the user's score, run through all chosen answers and calculate a number based on that. Do this every time you want to display the user's score, so the score is always up to date and accurate.
Related
I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .
Hello everyone so I have partly working code. However I also have issues with it. But let me start off to tell you what I am trying to achieve... On my site I have a login facility which sends all users to a home page once and only if the user is logged in. I would like to display who else is logged in on my page showing there usernames in a list.
My codes current ability...
Okay so i can code it to add the users on joining the site to a database and also then display each user on that database into a div which is great as it displays everyone online...
Where the problem stands...
However, when a user leaves the page there username needs to be deleted from the online user database. In the past I would simply do this with a on window close option in java. But due to Google safari and Firefox no longer supporting this option I am forced to find another way of doing it.
What the code bellow does...
So the code bellow loads an interval so after so much time it will repeat the code within it. The code first adds the user to the database, it then displays the user in a list on the site and then it deletes the user from the database just in case they are to then go offline.
Where the problem stands...
This all being very well for one user, but once a second user gets involved there intervals fall at a different time. So I have deleted the user from the database after it shows the list but then it means the second user displays the database and the first user isn't in it as they are deleted... This also causes a problem should a user go offline half way though the function happening, then it leaves them in the database and doesn't get around to deleting them out of the database.
The following is the java code...
$(document).ready(function() {
var user_name = "<?php print $username ?>";
setInterval(function() {
$.post('onlineusers.php', { name: user_name, action:"joined" });
$.post("onlineusers.php", { action2: "list" }, function(data){
$('#listusers').html(data);
});
$.post("onlineusers.php", { nameleft: user_name, action3:"left" }, function(data){
$('#errorrreport').html(data);
});
}, 5000);
}):
Now there is the PHP document code
//------------User joined page put into database --------
if( $_REQUEST["name"])
{
$user_name = $_REQUEST['name'];
};
if( $_REQUEST["action"])
{
$action = $_REQUEST['action'];
};
if ($action == 'joined') {
user_joined($user_name);
};
//-----------Listing online users within page -------------
if( $_REQUEST["action2"])
{
$action2 = $_REQUEST['action2'];
};
if($action2 == 'list') {
foreach (user_list() as $user){
echo $user . "<br />";
};
};
//------------ User left delete from the database ------------
if( $_REQUEST["nameleft"])
{
$user_nameleft = $_REQUEST['nameleft'];
};
if( $_REQUEST["action3"]){
$action3 = $_REQUEST['action3'];
};
if($action3 == 'left') {
user_left($user_nameleft);
};
//------ Functions what to do... --------
function user_joined($user_name) {
$user_name = mysql_real_escape_string(htmlentities($user_name));
mysql_query("INSERT INTO users (user_name)VALUES('$user_name')") or die("this didn't happen");
}
function user_left($user_nameleft) {
$user_name = mysql_real_escape_string(($user_nameleft));
$query = mysql_query("DELETE FROM users WHERE user_name = '$user_nameleft'")or die("failed to delete from table");
}
function user_list() {
$user_list = array();
$users_query = mysql_query("SELECT user_name FROM users") or die ("Unable to collect userlist");
while ($users_row = mysql_fetch_assoc($users_query)){
$user_list[] = $users_row['user_name'];
}
return $user_list;
}
The above code
Sorry it is slightly messy due to my recoding of it so many times in order to get it to work.
I would appreciate it if anyone could give me any help towards getting this to work. Now if it's not just simple off the code from above I can add the user to the online user database on entrance to the page and get it to list who is online frequently from listing the users on the database.
The real issue and where i am asking for your help with please...
However, if you have any idea on the code for the following that would be great... The user leaving the page is where the problem comes up. I need some method of checking the user is still active and if they are not then deleting them from the database so when the list then refreshes the user is no longer on the list. Such as pinging something until it ends up with no response and deletes the user from the database.
As my current code has problems with multiple users and synchronization of the interval function it needs to take that into account different users will see the list refresh at different times.
P.S. I have also looked at using $SESSION however i am still not sure on how to make this work with checking for offline users and then deleting them from the database this might be a method of doing it.
Thank you, I hope there is enough information to go on.
I've taken a different approach:
JS:
Loop of 5 seconds, AJAX requests onlinenow.php and displays the returned html in the online users box - This is mostly copied and pasted from W3C with the URL changed.
setInterval("getOnline()",5000);
function getOnline()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("onlineNow").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.path.com/to/onlinenow.php",true);
xmlhttp.send();
}
PHP:
Takes user/ip/identifier and stores/updates that + unix timestamp in the DB
Returns a list of all rows with unix timestamp in the past 10 minutes
<?php
header('Access-Control-Allow-Origin: *');//Pretty sure this enables cross domain AJAX
$session = $_SERVER['REMOTE_ADDR'];
$time=time();
$time_check=$time-60; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="pass"; // Mysql password
$db_name="custom"; // Database name
$tbl_name="table"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
// Check if user is already in the DB
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
//User is not in the DB, lets add them
$sql1="INSERT INTO $tbl_name(session, time, ip)VALUES('$session', '$time', '".$_SERVER['REMOTE_ADDR']."')";
$result1=mysql_query($sql1);
}
//Update this user's entry
else {
//User is in the DB, Update their entry
$sql2="UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
//Done updating info, time to get the user list
// if over 10 minute, delete session - Could just get all in past 10 mins instead
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
//Get total users (Could get a list of names if you preferred and store the info)
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
if ($count_user_online == 1) {
$plur = "";
}
else {
$plur = "s";
}
echo " $count_user_online user".$plur." online now ";
// Close connection
mysql_close();
?>
I've used this logic several times with and without usernames shown (sometimes just a number).
The code, of course, could be improved, but the basic principle is a fairly good solution.
You could try instead of deleting to include a timestamp (server based) when inserting.
Then have the javascript code insert/update every minute or so.
Then your query of who's on is simply which rows have a recent timestamp (like the last 65 seconds)
You'll have to clear out old rows in the table eventually, of course, unless you want a log of everyone who was ever on and when.
I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.
my question is on adding the file paths to images to a user's slot in a database. here is a sample, this is the page where the photos are to be chosen:
require_once("script.php");
<form method="post" action='golf.php'>
<?php
require_once("golf_phot.php");
?>
</div>
<input id="butt" type="submit" value="add"/>
</form>
here are the contents of golf_phot.php:
$query="SELECT category_id FROM categories WHERE category_name='golf'";
$resultt=mysql_query($query);
$row=mysql_fetch_array($resultt);
$do=$row['category_id'];
$query2="SELECT photo FROM all_photos WHERE all_photos.category_id='$do'";
$result=mysql_query($query2);
while ($row=mysql_fetch_array($result))
{
$photo=$row['photo'];
echo "<input type=\"checkbox\" name=\"addlist[]\" value=\"".$photo."\">"."<img src=\"".$photo."\">";
echo "<br>";
echo "<br>";
echo "<br>";
}
i already did the mysql connection and database selection, i won't post that but it has no issues. here are the contents of "script.php":
if(isset($_POST['addlist']))
{
$pics=$_POST['addlist'];
$n=count($pics);
//now, to open the database user_info, using the stored session
//make the session variable legit
if(isset($_SESSION['user']))
{
$user=$_SESSION['user'];
}
//get the user's id from the user_info table
$querya="SELECT * FROM user_info WHERE user_info.fb_id='$user'";
$result1=mysql_query($querya);
//now that we have the id, we can add the photos to
//user_photos, using their id as a foreign key
if(mysql_num_rows($result1)>0){
$rowa=mysql_fetch_array($result1);}
$user_id=$rowa['USER_INFO_ID'];
//before we add them, we'll need to see whether they exist or not.
//adding time:
for($i=0;$i<$n;$i++){
$data=$pics[$i];
$queryb="SELECT * FROM user_photos";
$result3=mysql_query($queryb);
if(mysql_num_rows($result3)>0){
while($rowa=mysql_fetch_array($result3))
{
$data2=$rowa['USER_PHOTOS'];
if($data==$data2)
{ $var='exists'; }
else{
$queryb="INSERT INTO user_photos(USER_PHOTOS_ID,USER_INFO_ID,USER_PHOTOS) VALUES('NULL','".$user_id."','".$data."')";
$result2=mysql_query($queryb);
}
}
}
}
// selected photos added to user's gallery!
}
the user data variables are all set as i use them elsewhere and they are successfuly added to the database, above, i include a way to see if the photo already exists, i don't add it if it does(maybe there's an issue with that?) so basically, the page with photos is loaded, the user checks on the photos they want and then they send it to the same page, where "script.php" is supposed to process the data and add it to the database. no photos are added to the database, i really can't tell what's the issue here. i kindly ask for help, even though this is probably an easy question, if you need me to clarify something, kindly ask so, meanwhile, can anybody help? thanks in advance.
One solution for check the picture is same or not is, using a hash algorithm on the pictures to determined the same pics.
i.e: (pseudo code)
$hash=sha1_file('pic-filename');
$sql='select * from image_table where hash_col ='.$hash;
if(num_rows($sql)>0)
//don't save pic.
else
// save the pic and it's hash value.
hash_col is a column in your image table that get the hash value of the particular image.
Please Try this code in your script.php. hoping this may work for you.
I Have removed the condition if(mysql_num_rows($result3)>0){
Code:
if(isset($_POST['addlist']))
{
$pics=$_POST['addlist'];
$n=count($pics);
//now, to open the database user_info, using the stored session
//make the session variable legit
if(isset($_SESSION['user']))
{
$user=$_SESSION['user'];
}
//get the user's id from the user_info table
$querya="SELECT * FROM user_info WHERE user_info.fb_id='$user'";
$result1=mysql_query($querya);
//now that we have the id, we can add the photos to
//user_photos, using their id as a foreign key
if(mysql_num_rows($result1)>0){
$rowa=mysql_fetch_array($result1);}
$user_id=$rowa['USER_INFO_ID'];
//before we add them, we'll need to see whether they exist or not.
//adding time:
for($i=0;$i<$n;$i++){
$data=$pics[$i];
$queryb="SELECT * FROM user_photos";
$result3=mysql_query($queryb);
while($rowa=mysql_fetch_array($result3))
{
$data2=$rowa['USER_PHOTOS'];
if($data==$data2)
{ $var='exists'; }
else{
$queryb="INSERT INTO user_photos(USER_PHOTOS_ID,USER_INFO_ID,USER_PHOTOS) VALUES('NULL','".$user_id."','".$data."')";
$result2=mysql_query($queryb);
}
}
}
First off, just wanted to say I'm a novice at this type of coding, although I'm hopeful that I'll eventually make sense of it all with a little guidance.
I have a MySQL database table (promotion) that stores a bunch of redemption codes for various products (for a give away contest). The idea is, the first person to enter the redemption code wins the product, and their info should be stored in the "promotion" table.
The table's columns are: redeem_id (Auto Increment field), redeem_code, redeemer_email, redeemer_first_name, redeemer_last_name, and redeem_date_time.
Initially, the redeem_id and redeem_code fields are the only ones with any data. What I'd like to happen is when a user enters their information (name, email, etc) and submit a redemption code, their info will populate the rest of the row for that particular code. If anyone else tries to submit a code that has already been redeemed, they should receive an error message - likewise for an invalid code (i.e. a code that does not exist in the table).
The PHP code I have so far is:
<?php
function get_promotion_by_redeem_code($redeem_code)
{
$sql = "SELECT * FROM promotion WHERE redeem_code= '".mysql_real_escape_string($redeem_code)."'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).", redeemer_first_name=".mysql_real_escape_string($first_name).", redeemer_last_name=".mysql_real_escape_string($last_name).", redeem_date_time=NOW(), WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
$insert = mysql_query($query);
return $insert;
}
$email=$_POST['e_mail'];
$first_name=$_POST['f_name'];
$last_name=$_POST['l_name'];
$redeem_code=$_POST['v_code'];
$connection = mysql_connect('localhost', 'db', 'pw');
mysql_select_db('db', $connection);
$promotion = get_promotion_by_redeem_code($redeem_code);
if ($promotion) {
if (!$promotion['redeemer_email']) {
redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code);
echo 'Congratulations, you have successfully claimed this item!';
} else {
echo 'Sorry, this item has already been redeemed.';
}
} else {
echo 'Sorry, you have entered an incorrect claim code. Please use your browser\'s back button to try again.';
}
mysql_close($connection);
?>
It works as expected when I enter an invalid claim code, or if a code's row has been previously populated.
When it doesn't work, is when someone goes to redeem the item for the first time. Essentially, it will show the "Congratulations" message, however the table doesn't get updated for the submitted information. Therefore, no matter how many times the correct code is entered, the user will receive the "Congratulations" message.
I'm fairly certain that the error is in the redeem_promotion() function, but I can't figure out where.
You have add an extra comma(,) before WHERE clause. Thats the mistake, i think.
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).",
redeemer_first_name=".mysql_real_escape_string($first_name).",
redeemer_last_name=".mysql_real_escape_string($last_name).",
redeem_date_time=NOW()
WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
**OR**
$query = "UPDATE promotion
SET redeemer_email='".mysql_real_escape_string($email)."',
redeemer_first_name='".mysql_real_escape_string($first_name)."',
redeemer_last_name='".mysql_real_escape_string($last_name)."',
redeem_date_time=NOW()
WHERE redeem_code='".mysql_real_escape_string($redeem_code)."'";
$insert = mysql_query($query);
return $insert;
}