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;
}
Related
I hope this is not a bad question. I've been trying to understand what I'm doing wrong but I can't.
I'm pretty new to php and mysql so I'm really confused...
I have this database (I will attach a mysql workbench model screenshot)
And I'm trying to insert the sales into sale and print_for_sale tables. The queries seem to be working and the data shows up in phpmyadmin. No error pops up. However the sale user in the sale table is always the same id. Even if I use a different user login. And in the print_for_sale table the fk_sale_id is always the same id. And the price_print_for_sale is always the same as well. That is not supposed to happen. What am I doing wrong?
Can anyone help me?
Thank you!
Here is my php code:
<?php
session_start();
$user_id = $_SESSION['user_id'];
print_r($_POST);
$id_print= $_POST['print_id'];
include('database.php');
$bought_sizes=$_POST['sizes'];
$number_of_bought_sizes= count($bought_sizes);
//header('location:index.php?area=printstore');
$sqlinsertsale = "insert into sale
(fk_sale_user,
fk_payment_id)
values(".$user_id.", 1)";
//payment is not yet defined so I'm using 1 just to try.
mysql_query($sqlinsertsale);
for($i=0; $i< $number_of_bought_sizes; $i++){
$selectmultiple = "select *
from print_has_size
inner join size on fk_size_id = size_id
inner join print on fk_print_id = print_id
where print_id =".$id_print."";
$resultmultiple = mysql_query($selectmultiple);
$linemultiple = mysql_fetch_assoc($resultmultiple);
$size_price = $linemultiple["size_price"];
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
$linesale = mysql_fetch_assoc($resultsale);
$sale_id = $linesale["sale_id"];
//$sale_id = mysql_insert_id();
/*PARA CADA 1 DOS TAMNHO*/
$sqlinsertprintforsale = "insert into print_for_sale
(fk_sale_id,
price_print_for_sale)
values(".$sale_id.", ".$size_price.")";
mysql_query($sqlinsertprintforsale);
}
?>
I'm also going to attach a screenshot of the selection page so you can see the markup in case it helps.
Edit:
(I'm adding the php code from where I check the user login)
<?php
session_start();
include('database.php');
$user=mysql_real_escape_string($_POST['user_login']);
$pass=mysql_real_escape_string($_POST['user_pass']);
$sql="select user_id, user_name
from user
where
user_login='".$user."'
and user_pass = MD5('".$pass."')";
echo $sql;
$result = mysql_query($sql);
$num_of_regs = mysql_num_rows($result);
echo "<br>".$num_of_regs;
if($num_of_regs!=1) {
header('location:index.php?login=done');
}
else {
$line = mysql_fetch_assoc($result);
$user_name = $line['user_name'];
$user_id = $line['user_id'];
$_SESSION['user_name'] = $user_name;
$_SESSION['user_id'] = $user_id;
header('location:index.php');
}
?>
And I did a log out system too.
<?php
session_start();
session_destroy();
header('location:index.php');
?>
Now I noticed that the sale table is not receiving data..
Only the print_for sale is. Wrong data still. Same IDs... Why? :(
This is the only error message that I get when I used the code
ini_set('display_errors', true); error_reporting(E_ALL);
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /Applications/XAMPP/xamppfiles/htdocs/printstore/database.php on line 7
Added
echo $_SESSION['user_id'];
And this is my output for user 1:
And for user 2:
it seems to be ok, it recognizes user 1 and 2.
Table sale is not being refreshed when I make a "new purchase" and table print_for_sale is refreshed with the same sale id. Always 3 (as shown in the screenshot)
I deleted every row from sale in phpmyadmin and tried again. It's working. Sale table seems to be working fine. The only problem now is the table print_for_sale which even when I use a different user (and it shows up ok in the sale table), it still shows the same sale_id and the same price_print_price which is always 25). And in this case I never selected anything costing 25. -
Give this a shot. It seems that you're getting the same result because you never loop through your results. Also make sure that your field names are exactly the same as your field names in your DB.
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
while($linesale = mysql_fetch_assoc($resultsale))
{
$sale_id = $linesale["sale_id"];
}
when you logout you should destroy your sessions
I assume you have a logout page like logout.php. In it you should set below lines. If you don't do that session values can't change.
<?php
session_start();
session_destroy();
?>
Also if you store your user id on a session variable, only closing all browser windows than reopen and login will help you.
Extra info for you future code life: WHY PDO http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
I have a MYSQL table with edit and delete links on each row. The edit link goes to edit_patient.php which has a form (actually, a copy of the form originally used to insert patient into the database). After few tries, the script is working although I guess it could be improved (indeed, I get a notice of "Undefined index: id" when I submit the edits. The ID is passed to the edit_patient.php file through a GET procedure. Relevant code as follows:
// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_patient.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p>Sorry, it is not possible to update patient info at this time</p>';
include ('../elements/layouts/footer.php');
exit();
}
And, after some clean up and check on submitted values:
if($action['result'] != 'error'){
// Make the query:
$q = "UPDATE `demographics`
SET lastname='$lastname', firstname='$firstname', clinic='$clinic', sex='$sex', dob='$dob', age='$age',
disease_1='$disease_1', disease_2='$disease_2', disease_3='$disease_3', address='$address', city='$city', country='$country',
zip='$zip', phone_1='$phone_1', phone_2='$phone_2', phone_3='$phone_3', email_1='$email_1', email_2='$email_2',
physician='$physician', notes='$notes'
WHERE dem_id=$id
LIMIT 1";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_affected_rows($db_connect) == 1) { // If it ran OK.
// Tell the user we have edited patient data successfully
$action['result'] = 'success';
array_push($text,'Patient data have been updated on databank');
}else{
$action['result'] = 'error';
array_push($text,'Patient data could not be changed on databank. Reason: ' .
'<p>' . mysqli_error($db_connect) . '<br /><br />Query: ' . $r . '</p>');
} // End of if (empty($errors)) IF.
} // End of if (empty rows))
Ok, so far so good. Now, in order to show already inserted data, I run another query:
// Retrieve the user's information:
$q = "SELECT lastname, firstname, clinic, sex, dob, age, disease_1, disease_2, disease_3, address, city, country, zip, phone_1,
phone_2, phone_3, email_1, email_2, physician, notes
FROM `demographics`
WHERE dem_id='".$_GET['id']."'";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.
// Get the user's information:
$row = mysqli_fetch_assoc ($r);
// Create the form:
Here, the critical row I do not understand is WHERE dem_id='".$_GET['id']."'"; --> If I it leave as it is, the script runs almost Ok but then I get a notice of undefined index id.
However, when I replace with WHERE dem_id=$id"; as in the first query, the script gives a fatal error of undefined variable: id.
Finally, to submit the form I use the following command:
" /> that is working Ok, but it is not working when I use:
" />
Can anyone help me to understand why, and how to correct the issue, I'd rather prefer to be able to use simply $id (I believe is straight forward and simple) but for some reason is not working as expected. Finally, I would like to be able to report in the form to be edited also data inserted with radio buttons and drop-down (select) menus. Any advice on that would be greatly appreciated !
Please make sure that your specific record has been updated after the submit button in your edit_patient.php ? If it works and after next which page is display ..? Is it is Display.php (i.e. all record display page ) ? Please be specify first and i really help you to solve your query.
I am having issues with php and mysql once again. I have a database setup with the table users and I want to make a SELECT COUNT(*) FROM users WHERE {value1} {value2} etc...but the problem is that the 3 fields I want to compare are not in order in the table and when trying the SELECT query, the result vairable($result) is NOT returned properly(!$result). Is there a way to check multiple fields in a mysql table that have fields in between them? Here is an example of what I want to accomplish:
A mysql table called users contains these fields: a,b,c,d,e,f,g,h,i,j,k,l and m.
I want to make a SELECT COUNT(*) FROMusersWHERE a='$_SESSION[user]' and d='$_SESSION[actcode]' and j='$_SESSION[email]' but the statement in quotes is my query and it always executes the if (!$result) { error("An error has occurred in processing your request.");} statement. What am I doing wrong? On the contrary, whenever I try the statement using only one field, ex a, the code works fine! This is an annoying problem that I cannot seem to solve! I have posted the code below, also note that the error function is a custom function I made and is working perfectly normal.
<?php
include "includefunctions.php";
$result = dbConnect("program");
if (!$result){
error("The database is unable to process your request at this time. Please try again later.");
} else {
ob_start();
session_start();
if (empty($_SESSION['user']) or empty($_SESSION['password']) or empty($_SESSION['activationcode']) or empty($_SESSION['email'])){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} elseif ($_SESSION['password'] != "password"){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} else {
$sql = "SELECT * FROM `users` WHERE `username`='$_SESSION[user]' and `activationcode`='$_SESSION[activationcode]' and `email`='$_SESSION[email]'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql);
if (!$result) {
error("A database error has occurred in processing your request. Please try again in a few moments.");/*THIS IS THE ERROR THAT WONT GO AWAY!*/
} elseif (mysql_result($result,0,0)==1){/*MUST EQUAL 1 OR ACCOUNT IS INVALID!*/
echo "Acount activated!";
} else {
error("Account not activated.");
}
}
}
ob_end_flush();
session_destroy();
?>
Try enclosing your $_SESSION variables in curly brackets {} and add or die(mysql_error()) to the end of your query -
$sql = "SELECT * FROM `users` WHERE `username`='{$_SESSION['user']}' and `activationcode`='{$_SESSION['activationcode']}' and `email`='{$_SESSION['email']}'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql) or die(mysql_error());
store your session value in another varibles then make query , i think
it's work proper
$usr=$_SESSION['user'];
$acod=$_SESSION['activationcode'];
$eml=$_SESSION['email'];
$sql = "SELECT * FROM `users` WHERE `username`='$usr' and `activationcode`='$acod' and `email`='$eml'";
$result = mysql_query($sql) or die(mysql_error());
I'm trying to implement a two-step registration form for my site wherein I used 2 separate pages in order to get the information from the user.
First Step:
if($submit)
{
$connect = mysql_connect("localhost","root","");
mysql_select_db("mydb");
$queryreg = mysql_query("INSERT INTO volunteerbio VALUES (<my insert values>)");
}
//gets the latest id added
$query = mysql_query("SELECT MAX(volunteerID) FROM volunteerbio");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while($row = mysql_fetch_assoc($query))
{
$dbaccountID = $row['volunteerID'];
}
header("Location: http://localhost/RedCrossCaloocan/registration2_volunteer.php");
$_SESSION['volunteerID']=$dbaccountID;
}
}
?>
What the first step does is that it creates a complete table row wherein the values needed for the second step will be temporarily left with blank values until they are updated in the next step.
Second Step:
<?php
session_start();
$idnum = #$_SESSION['volunteerID'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mydb");
if($submit)
{
$updateSkills = mysql_query("
UPDATE volunteerbio
SET medicalSkillRating = $medicalRating,
electronicsSkillRating = $electronicRating,
errandSkillRating = $errandRating,
childCareSkillRating = $childCareRating,
counsellingSkillRating = $counsellingRating,
officeSkillRating = $officeRating,
communicationSkillRating =$communicationRating,
carpentrySkillRating = $carpentryRating
WHERE volunteerID = $idnum;
");
}
?>
The second step basically updates the fields which where filled with blank values during the first step in order to complete the registration.
The first step already works and is able to add the values to the database however, I am having a problem on updating the blank values through the second step.
I have a feeling that there may be a problem regarding my usage of sessions in order to get the newly generated ID from the first step, but I just can't figure it out.
You are doing:
header("Location: http://localhost/RedCrossCaloocan/registration2_volunteer.php");
$_SESSION['volunteerID']=$dbaccountID;
The second line MAY never get executed, because you do a redirect before it. I say MAY because it MAY get executed. You have to add exit(); after all redirects to prevent further execution of the script.
Another thing:
Never suppress warnings in PHP using #. The # is almost never needed. So instead of doing:
#$_SESSION['volunteerID'];
You should do:
if (isset($_SESSION['volunteerID'])) {
$idnum = $_SESSION['volunteerID'];
} else {
// something went wrong???
}
I can't see it in your example, but do prevent SQLi vulnerabilities?
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.