Problems implementing "Save" feature on website - php

Here's my code:
<?php
session_start();
$currentPage = $_POST["currentPage"];
$passedCoupID = $_POST["passedCoupID"];
/*
if youre logged in, save
if not, take you to the register page with an option to go right back to the coupon if you dont want to register
*/
$con = mysql_connect("localhost","admin","admin");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("users", $con);
if($_SESSION["loggedIn"] == 1)
{
$userID = $_SESSION["userID"];
mysql_query("INSERT INTO users_saves (userID, couponID) VALUES ('$userID', '$couponID')");
mysql_select_db("coupons", $con);
mysql_query("UPDATE stats SET saves = saves + 1 WHERE id = '$couponID'");
header('Location: ' . $currentPage);
}
else
{
header('Location: register.php');
$_SESSION["goBack"] = $currentPage;
}
?>
What I'm trying to do is when the user clicks the "Save" button on a page, it will go to this form, which will insert both the user's ID and the coupon's ID into the table users_saves. Then I want it to change databases and increment the row saves at the id of the saved coupon. It looks fine to me, and it works without errors, but it writes 0, 0 to the table users_saves instead of either of the values, and I'm not sure why. Also, there is no increment of saves when I do the database switch.

Well, your variable seems to be called $passedCoupID, while in the sql you are referencing $couponID
that might be your problem right there. You should turn on all errors, then you'll probably see a lot of "notice" errors in your code.

Related

PHP login system help needed for deletion

Help with user deletion:
Hello I am creating a user creation system for a project of mine, I am still very new to PHP, my issue is getting the user from the MySQL database and then deleting it, I will show you my code below:
<?php
require_once("config/db.php");
if ($login->isUserLoggedIn() == true) {
if ($_SESSION['user_perm'] == 1) {
//Create Connection
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Check connection
if ($db_connection->connect_error) {
die("Connection failed: " . $db_connection->connect_error);
}
$sql = "SELECT user_name FROM users";
$result = $db_connection->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["user_name"];
$user_name_delete = $row["user_name"];
$_SESSION['user_name_delete'] = $user_name_delete;
echo 'Delete User<br>';
}
}
}
$db_connection->close(); ?>
On the deleteuser.php page my code is, note this was just a test:
<?php
echo $_SESSION['user_name_delete'];
?>
My issue with this is grabbing the user who you selected to delete as at the moment it only outputs the last user grabbed from the database.
Any help is much appreciated.
This value:
$_SESSION['user_name_delete']
Is going to contain only the last user in your data. Because you keep overwriting it in your loop:
$_SESSION['user_name_delete'] = $user_name_delete;
The short answer is... Don't use session state for this. (Really, you shouldn't use session state for much of anything unless you absolutely have to.) The identity of the user to be deleted should be included in the request to delete the user. In this case, you can add it to the link. Something like this:
echo 'Delete User<br>';
(Or whatever you use to identify the user in the data row.)
Then in deleteuser.php you can get that value from:
$_GET['id']
Validate the inputs, validate that the user is authorized to perform the delete, and then use that value in the WHERE clause of your DELETE query.
Get the users id and insert it into a delete query.
$id = $db->real_escape_string($_GET['id']);
$sql = "delete from users where id = " . $id; and then run the query to delete the user from the database.

Session Confliction Error

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.

separate sessions

When someone logs in on my website, it will output information just for that user and so on. But there is a problem as it seems it doesn't recognise different users. If I log in two users on the website, first one will become second one... here is my code at the start of each page
?php
session_start();
require_once 'loginDetails.php';
$db_server = mysql_connect("$db_hostname", "$db_username",
"$db_password");
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SESSION['username']))
{
$user = $_SESSION['username'];
$query = mysql_query("SELECT * FROM cssh_students_table WHERE StudentUserName = '$user'");
$query1 = mysql_fetch_row($query);
$course = $query1[10];
$year = $query1[6];
$email = $query1[4];
$loggedin = TRUE;
}
else
{
$loggedin = FALSE;
}
if ($loggedin == FALSE)
{
session_unset();
session_destroy();
header('Location: ../index.html');
}
?>
session_destroy() is not guaranteed to kill your session cookie. Your problem is probably because your original session cookie still exists.
See this related question.
Additional (Not Related)
Doing a SELECT * and then accessing the results using integer indexes is a bad practice that will eventually cause you problems some day when the database structure is changed. Either SELECT the items you need, or use mysql_fetch_assoc and access the values by name.
There can be many solutions for that.
For us, we need to do that kind of thing in development. For each user we want to open, we use an anonymous browser window. Another solution could be to use a different domain name for each user you want to login (with a dns wildcard).

Multiple Step Registration Form PHP/MySql using sessions

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?

How to echo out info from MySQL table in PHP when sessions are being used.

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).

Categories