Am creating a website where people can leave their opinions on releases by rating them and this gets stored into a MySQL database which is driven by PHP.
I have a feedback form for one particular release, which (lets say in this example) has the ID of 35. When I send a user another one which has the ID of 36 and the user has both windows open, the PHP processing code stores the responses from ID 35 but with ID 36. The page redirects to the previous page when the database already has a 'reaction_reacted' value of '1'.
Is there a way to solve this?
Here is an example of my code. The $promo_id, reaction_id and username are passed to it from the previous page when submission occurs.
session_start();
include 'connect.php';
mysql_connect($host,$db_user,$db_password);
mysql_select_db($database);
$promo_id = $_SESSION['promo_id'];
$reaction_id = $_SESSION[reaction_id];
$username = $_SESSION['username'];
if(isset($_SESSION['username']))
{
// Check to see if Receipt and DJID values are entered
$queryb = "select reaction_ID from reactiondata where reaction_ID='$reaction_id' AND reaction_username='$username' AND reaction_promoID='$promo_id' and reaction_reacted='1'";
$result2 = mysql_query($queryb) or die(mysql_error());
while($row = mysql_fetch_array($result2)){
header('Location: ' . $_SERVER['HTTP_REFERER']);
// session_destroy();
// exit;
}
if ($reaction_id && $promo_id != null)
{
$p4support = $_POST['DJsupport'];
$p4favouritemix = $_POST['FavMix'];
$p4score = $_POST['score'];
$p4comment = $_POST['DJcomment'];
$query = "UPDATE reactiondata SET reaction_username='$username', reaction_promoID='$promo_id', reaction_support='$p4support', reaction_favouritemix='$p4favouritemix', reaction_score='$p4score', reaction_comment='".mysql_real_escape_string($p4comment)."', reaction_reacted='1' WHERE reaction_ID='$reaction_id'";
mysql_query($query) or die('Error in MySQL query. Here is the error message: '.mysql_error());
$query7 = "UPDATE reactiondata SET reaction_time=NOW() WHERE reaction_ID='$reaction_id'";
mysql_query($query7) or die('Error in MySQL query. Here is the error message: '.mysql_error());
}
Thanks
CP
P.S I know I am using depreciated mysql_query methods, I just want the page to function properly before I start preventing SQL Injection attacks.
The easiest solution (one of the...) is to add the reaction_id as a hidden form field to the form instead of using a session. That way the reaction is always linked to the correct ID when the form is posted.
You should not use a session for that as the session will span all open windows and tabs in the browser so it is not suitable to maintain the state of a specific tab.
Related
I've got an update query running so that events in the database can be updated.
For example, the event record table :
Now, when I want to edit the record, I import all the current data from one and show it on a webpage, so that the user can edit the data, as shown:
However, if I submit that page and the event description is more than a few characters long it does not update at all. Here is my PHP/MySQL Code:
$event_title=$_POST['event_title'];
$event_desc=$_POST['event_desc'];
$event_date_start = $_POST['event_date_start'];
$event_date_end = $_POST['event_date_end'];
$db = mysql_select_db("millyaca_events", $connection);
mysql_query("UPDATE events set event_title='$event_title', event_desc='$event_desc', event_date_start='$event_date_start', event_date_end='$event_date_end' where unique_ID='$ID'", $connection);
Only just started learning PHP and MySQL so apologies if it's a really stupid mistake.
Here is the complete submit button script:
if (isset($_POST['submit'])) {
$ID = $_GET['ID'];
$event_title=$_POST['event_title'];
$event_desc=$_POST['event_desc'];
$event_date_start = $_POST['event_date_start'];
$event_date_end = $_POST['event_date_end'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "removed username", "removed password");
// Selecting Database
$db = mysql_select_db("millyaca_events", $connection);
// SQL query to fetch information of registerd users and finds user match.
mysql_query("UPDATE events set event_title='$event_title', event_desc='$event_desc', event_date_start='$event_date_start', event_date_end='$event_date_end' where unique_ID='$ID'", $connection);
mysql_close($connection); // Closing Connection
header("location: https://www.millyacademy.com/admin-zone/events_management/"); // Redirecting To Other Page
}
From the comments we've debugged this to being an apostraphe/quote in the data being passed to the query. To resolve this with your current DB driver use, mysql_real_escape_string, http://php.net/manual/en/function.mysql-real-escape-string.php.
You should switch to MySQLi or PDO though in the future and use prepared statements.
Here's a functional usage (untested, so maybe not functional?) using your current code.
if (isset($_POST['submit'])) {
$ID = (int)$_GET['ID']; //force this to an int, or you could also escape
$event_title= mysql_real_escape_string($_POST['event_title']);
$event_desc= mysql_real_escape_string($_POST['event_desc']);
$event_date_start = mysql_real_escape_string($_POST['event_date_start']);
$event_date_end = mysql_real_escape_string($_POST['event_date_end']);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "removed username", "removed password");
// Selecting Database
$db = mysql_select_db("millyaca_events", $connection);
// SQL query to fetch information of registerd users and finds user match.
mysql_query("UPDATE events set event_title='$event_title', event_desc='$event_desc', event_date_start='$event_date_start', event_date_end='$event_date_end' where unique_ID='$ID'", $connection);
mysql_close($connection); // Closing Connection
header("location: https://www.millyacademy.com/admin-zone/events_management/"); // Redirecting To Other Page
}
It is best to never pass user data directly to your queries.
Two Things.
Escape the data provided by user , that will take care of any quotation .
Ensure the db field you are trying to update has enough length.
Also it may be worth skipping the entire POST and do the update using hard coded values to see what is happening.
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
First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.
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?
I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).