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
Related
Logging in we of course have set the $_SESSION['username'] and $_SESSION['password'] as usual. However I am then trying to pack that into a variable for use around the site:
$logged = mysql_query("SELECT * FROM `users` WHERE `username`='$_SESSION['username']' AND password = '$_SESSION['password']'");
$logged = mysql_fetch_array($logged);
One previous setups, this has enabled me to then use $logged around the site for various reasons, such as calling the logged in users email to echo in a form,
However, this time, when using this method, it fails to echo anything. I have tried using the session username variable which works to echo the username, but then I tried using the session to echo the email and it didn't work.
If someone could help me pinpoint why this is, I'd be grateful.
It just doesn't seem to be pulling any information from the user as it should.
For me this just seems like an escape-thing. Try
$logged = mysql_query("SELECT * FROM users WHERE username='".$_SESSION['username']."' AND password = '".$_SESSION['password']."'");
$logged = mysql_fetch_array($logged);
Also make sure to call session_start(); before sending any headers/echoing anything if you weren't aware.
Off topic-tip
As long as this query isn't used in anything public, it's fine. But if you're gonna use this code for anything, be sure to slash your query variables. If not, and if my credentials are not validated nor hashed, you could do some nasty SQL injection by setting your password to be something like '; DELETE * FROM USERS;# as the query would then say SELECT * FROM users WHERE username='JohnDoe' AND password = ''; DELETE * FROM USERS;#'
for the usage of session
if(!session_id())
session_start();
the above session start is a must in every page.
use print_r($_SESSION); to check the session variables initialized..
once done (try using mysqli insted of mysql)
$sql='SELECT col1, col2, col3 FROM table1 WHERE condition';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$arr = $rs->fetch_all(MYSQLI_ASSOC);
}
foreach($arr as $row) {
echo $row['co1'];
}
comment your progress for further changes..
<?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,
All security issues aside.
I have created some session data. This session data includes a
username stored under "myusername".
I have also created an html form that adds a row to one of my
tables.
I am trying to get some data retrieved from a query (using the session data) to be put in with the form data that has been submitted.
Essentially create a record of who submitted the data.
Here is my code:
<?php
session_start();
if ( isset( $_SESSION['user'] ) ){
header("location:failedlogin.html");
}
echo $_SESSION['myusername'];
var_dump($_SESSION);
//Connect
$con= mysql_connect("localhost","root","password");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("database1", $con);
//create Get UserId from user
$result= mysql_query("SELECT UserId FROM user
WHERE UserName='{$_SESSION['myusername']}'");
//I think this is where the problem is
//execute query and store results
if($result){
$data = mysql_fetch_assoc($result);
}
//insert form data and $data into database 1
$sql="INSERT INTO bug
(bugName, bugBy, bugPriority, bugFor, bugContainer, bugFixed, bugCommentCount)
VALUES ('$_POST[bugname]','$data[0]','$_POST[bugpriority]',
'$_POST[bugfor]','$_POST[bugcontainer]','0','0')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }
mysql_close($con)
?>
I can't seem to get get it to submit the data from the SELECT query, the form data goes through fine.
Sorry if I've laid this out terribly. I'm finding it hard to understand what I've done wrong, so I don't know how to explain what I'm looking for very well.
Thanks for any and all help! Let me know if you need more information.
Your SQL statement is incorrect, the variables require escaping.
"...VALUES('". $_POST['bugname'] . "')";
As you currently have it $_POST[bugname] will try to find a constant global variable called 'bugname'. This will not exist.
However, $_POST['bugname'] will reference the correct key within the array.
I have to mention that this is not only a terrible way to create a SQL statement, It is also very insecure.
You're using fetch_assoc, so it's returning an associative array:
instead of $data[0]
insert $data['UserId']
If that doesn't do it, have you check to see if $data has anything before your insert statement?
p.s. you should learn PDO: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
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.
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.