0

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?

1

2 Answers 2

1

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();
?> 
Sign up to request clarification or add additional context in comments.

1 Comment

This is working. Thanks for letting me know this is vulnerable to sql injection. Is there a way to avoid this?
0

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

1 Comment

Thanks i will keep an eye on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.