Fille
Fille

Reputation: 23

php store session variable in mysql database

I have a website in PHP. I try to store the session variable $_SESSION['user_name'] to a mysql database when a logged in user visits a specific webpage on my site.

<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users 
VALUES ('.$_SESSION['user_name'].')';

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

Error message:

Notice: Undefined variable: _SESSION in /opt/lampp/htdocs/succes.php on line 16

Tried a bunch of things but can't figure it out. What is wrong here?

Upvotes: 0

Views: 3225

Answers (2)

Todd Johnson
Todd Johnson

Reputation: 3

Before you use any $_SESSION variables you need to call session_start().

Of topic a bit though, something to look into PDO. It can be a bit a tad slower than mysqli() however supports many more Database types. Here is a good article on Tuts+ explaining some of the differences as well as explaining essential security steps.

If I could be a bit biased I have created a PHP Class for PDO Connections which can be found on GitHub

Upvotes: 0

elixenide
elixenide

Reputation: 44851

You need to call session_start() at the beginning of your script (before using any $_SESSION variables). Also, you need quotes around the variable in you query:

$sql = 'INSERT INTO users 
VALUES ("'.$_SESSION['user_name'].'")';

Please note that this is not safe; you are wide open to SQL injection. Instead, you should use prepared statements:

<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users 
VALUES (?)';

$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_SESSION['user_name']);

if ($stmt->execute()) {
    echo "New record created successfully";
} else {
     echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

Upvotes: 1

Related Questions