Inserting session data to mysql database - php

<?php
session_start();
if (!isset($_SESSION)){
}
$total_amt=$_POST['total_amt'];
$total_seats=$_POST['total_seats'];
$boarding_point=$_POST['boarding_point'];
$_SESSION['total_amt']=$total_amt;
$_SESSION['total_seats']=$total_seats;
$_SESSION['boarding_point']=$boarding_point;
?>
<?php
require_once("config.php");
$source_point=$_SESSION['source_point'];
$destination=$_SESSION['destination'];
$datepick=$_SESSION['datepick'];
$_SESSION['total_amt']=$total_amt;
$_SESSION['total_seats']=$total_seats;
$boarding_point=$_POST['boarding_point'];
// Insert data into mysql
$sql="INSERT INTO book_seat(from, to, datepick, total_amt, total_seats, boarding_point) VALUES
'{$_SESSION['source_point']}',
'{$_SESSION['destination']}',
'{$_SESSION['datepick']}',
'{$_SESSION['total_amt']}',
'{$_SESSION['total_seats']}',
'{$_SESSION['boarding_point']}')";
$result=mysql_query($sql);
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
if(!$sql) die(mysql_error());
mysql_close();
?>
I want to insert my session variables to my database..
This is my code, there is no error happening, page is redirecting to booking_detail.php but also these session variables are not getting inserted to my database also..

From and to are reserved word,use backticks
Reserved words in Mysql
$sql="INSERT INTO book_seat(`from`, `to`, datepick, total_amt, total_seats, boarding_point) VALUES
'{$_SESSION['source_point']}',
'{$_SESSION['destination']}',
'{$_SESSION['datepick']}',
'{$_SESSION['total_amt']}',
'{$_SESSION['total_seats']}',
'{$_SESSION['boarding_point']}')";

Comment out your header(), turn on error reporting using error_reporting(-1), check mysql_error() and then fix that problem.
From now I can see that you've got syntax error in sql query because you're using from as column name which is restricted word. You have to put it in `.

remove the space from top
<?php session_start();
if this didn't work
var_dump($_SESSION) before inserting to check value exist in the session
and use die(mysql_error()); with the query
$result=mysql_query($sql) or die(mysql_error());;

if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
Above code will be executed once the form is submitted if chksbmt is the name of the submit button.
It takes to that page mentioned in header before inserting.
Write all your stuff in between above curly braces, use
if(isset($_POST['chksbmt']) && !$errors)
{
//all your stuff, ex:storing in DB.
if($result){
header("location:booking_detail.php");
}
}
I hope that I've understood your problem, this will workout.

First remove quotes from all session variables like:
{$_SESSION['source_point']}
Second you're redirecting before mysql_error check, Check on results and error first and then redirect:
if (!$result) {
die(mysql_error());
}
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}

1) Start session if its separate script.
2) Remove reserved keyword as suggested by #Mihai in your query.
3) In your query It should be VALUES( instead of VALUES.
4) As you are mention in your comment leaving_from not inserting into Db.
Because in your script you have not assign session value for $_SESSION['source_point'] .
In your script will be :-
<?php
session_start();
if (!isset($_SESSION)){
}
$total_amt = $_POST['total_amt'];
$total_seats = $_POST['total_seats'];
$boarding_point = $_POST['boarding_point'];
$_SESSION['total_amt'] = $total_amt;
$_SESSION['total_seats'] = $total_seats;
$_SESSION['boarding_point'] = $boarding_point;
// Set here session value for $_SESSION['source_point'] as well,

Related

empty session value when moving one page to other

Im having a problem of accessing the session variable value.
im creating a login page and this were i set the values of my session variables.
index.php
<?php
session_start();
$result=mysql_query("select * from myuser where id='".$id ."' and password='".$password."'");
if(mysql_num_rows($result) > 0){
$user = mysql_fetch_assoc($result);
$_SESSION['SESS_ID'] = $user['id'];
$_SESSION['SESS_UNAME'] = $user['username'];
$_SESSION['SESS_PASS'] = $user['password'];
header("location:home.php");
exit();
}
?>
home.php
<?php
session_start();
if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID'])) == ''){
header("location:index.php");
exit();
}
?>
<html>
<body>
<p>Login Successful</p>
<?php echo $_SESSION['SESS_ID'] ; ?>
</body>
</html>
the problem here is i have no value in $_SESSION['SESS_ID']..so how do i get or access the value of this session variable in my home.php?
Edit: my query for the SQL is
select * from myuser where id='".$id ."' and password='".$password."'
Some points about why you have this issue:
the values you populate the $_SESSION array with come directly from the database, but you have no database SQL query - instead you have
"!--query written here --"
If you can replace this placeholder with a query that returns your id, username and password values then your code should execute as expected.
I'm not certain if your syntax is wrong as such, but it is not the shape I would ever lay it out, my own shape would be:
$result = mysqli_query($connection, $sql);
while ($outputrow = mysqli_fetch_array($result)){
// In here $outputrow is an array of ONE row of your database, so
// $outputRow['id'] = the id from one row. ordered by the ORDER BY in your SQL query.
}
Add a mysqli_error($connection) clause to your SQL query to detect errors. such as :
Here:
$result=mysqli_query($connection, "<!--query written here -->") or die("error :".mysqli_error($connection));
As I have used across these examples, please, please STOP using MySQL and use at least MySQLi or even PDO. There are a host of improvements and bug fixes and lots of info on this transition on SO.
Also, never, ever compare passwords as strings, passwords saved to a database should as a minimum be saved as hashes with PHP function password_hash(). Never have the line if($_POST['pwd'] == $row['pwd']){.
Finally, as rightly mentioned by Fred-ii- in comments, add error logging and checking into your script so that you know what's going on:
Such as:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Add these to the very top of your PHP page and they will display your errors and warnings to you so you can see what is and is not working.
EDIT:
From your edit there are two biq questions, your statement is that:
"select * from myuser where id='".$id ."' and password='".$password."'
so where does the value $id and $password come from? is the <?php at the top of the page, if so, these variables will always be empty, you need to apply a value to these variables.

MYSQL Tables Picky About Fields?

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());

Why Isnt The Session Being Inserted Into Database?

Why can't I insert my session into my database? I'm sure I have used the same line of code elsewhere numerous times and it has worked for me till now.
<?php
$id = $_GET['election'];
$vote = mysql_real_escape_string($_REQUEST['vote']);
$vote = mysql_real_escape_string($_REQUEST['vote']);
$sql= "INSERT INTO votes (election_id, ni) VALUES ('$id', '". $_SESSION['ni']."')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
else
{
echo '<hr><h4>Your Vote Has Now Been Casted </h4><hr><h5> My Account</h5>';
}
?>
any ideas? the field ni comes out with the number 0
Try using
session_start();
at the beginning of the file so the session variable will be set and initialized.
I don't think this has anything to do with being a database specific issue, if before that code runs if you insert:
var_dump($_SESSION['ni']);
exit;
Does $_SESSION['ni'] contain anything other than 0? Also have you called session_start() before you try and access the $_SESSION object?
http://php.net/manual/en/function.session-start.php

Trouble with updating Data trough PHP

I have a problem with this code, it does delete a row but not editing one. I cannot figure out how to make it work.
Here's the script:
<?php
if($_POST['delete']){
$i = 0;
while(list($key, $val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id='$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
// if successful redirect to delete_multiple.php
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=data.php">';
}
}
if($Submit){
for($i=0;$i<$count;$i++){
$sql="UPDATE $tbl_name SET naam='$naam[$i]', achternaam='$achternaam[$i]', leeftijd='$leeftijd[$i]', straat='$straat[$i]', postcode='$postcode[$i]', telefoon='$telefoon[$i]', email='$email[$i]', geslacht='$geslacht[$i]', pakket='$pakket[$i]', WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
mysql_close();
?>
As others have pointed out $Submit isn't defined before the if statement - also $tbl_name isn't defined either so it would bring back an error if the if statement was triggered.
Also in $result1 you used $sql1 - $sql1 has not been defined.
You're vulnerable to SQL injections like Pekka said, so I advise reading up on it, always, ALWAYS validate user inputted data, never trust anyone :)
Also, you don't need to print a meta refresh, you can just use header
header ("Location: data.php");
$Submit is not defined before it is used. So, its value will be null which is a falsy value. Hence if loop will never get executed.
$Submit is not defined (as others already mentioned). Also, if you do define $Submit then $count is still undefined. So you still won't get into the for loop. And if $count is defined, your code still does not update the database. You store your sql query in $sql but pass $sql1 , which has not been set, as query that should be executed.
And your code is wide open for sql injection. You should not want that.

PHP MYSQL Warning: mysql_query() expects parameter 1 to be string, resource given in

<?php
include 'connect.php';
include 'header.php';
$page = "signup.php";
// receive the invite code:
$code = $_POST['code'];
$sql = "SELECT codes FROM invites WHERE codes='$code'";
// check the table for matching codes
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) {
// end any previously defined sessions.
session_start();session_unset();session_destroy();
// start a new session
session_start();
// define the session variable.
// this allows us to check if it's set later and is required for
// the script to run properly.
$code = $_POST["code"];
mysql_query("DELETE FROM invites WHERE codes='$code'");
header('Location: '.$page);
exit;
} else {
echo "Invite invalid. Please try again later.";
echo $code;
}
include 'footer.php';
?>
I am trying to implement an invite system to a webpage I am working on. However when trying to evaluate if there is a row containing the invite code I keep either getting nothing or this warning. The warning in this case but if I change the if state to ==1, it allows everyone regardless of code and ==0 does throws different errors.
if (mysql_query($result)) {
Try mysql_num_rows there.
There are a few things wrong here.
1) SQL Injection vulnerabilities, don't ever pass a superglobal $_POST or $_GET or any other user-supplied variable directly inside your query!
Use at minimum mysql_real_escape_string() to the variable before letting it into the query, or better look into parametrized queries, it's the best way to avoid SQL vulnerabilities
2)
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) ....
This doesn't check if request returns 1 or 0 rows, you should use mysql_num_rows() here instead
if(mysql_num_rows() == 1) //or whatever you need to check
3)
session_start();session_unset();session_destroy();
// start a new session
session_start();
session_start() should be called before anything in your page. Don't know why this redundancy of calling, unsetting, destroying, recalling it here. If you want another id, just use session_regenerate_id();
And as already said by other, use some error reporting in your query, something like
$result = mysql_query($sql) or die(mysql_error())
to actually see what's failed, where and why.
Problem is your query. First of all check your statement and use this :
$result = mysql_query($sql) or die(mysql_error());
instead of this
$result = mysql_query($sql);
So, you can see are there any error at your SQL query .

Categories