我有一个PHP网站。当登录用户访问我网站上的特定网页时,我尝试将会话变量$_SESSION['user_name']
存储到mysql数据库。
<?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();
?>
错误讯息:
注意:未定义的变量:第16行的/opt/lampp/htdocs/succes.php中的_SESSION
尝试了很多东西,但无法弄明白。这有什么不对?
答案 0 :(得分:0)
您需要在脚本开头调用session_start()
(在使用任何$_SESSION
变量之前)。此外,您在查询中需要围绕变量的引号:
$sql = 'INSERT INTO users
VALUES ("'.$_SESSION['user_name'].'")';
请注意, 不 安全;你对SQL注入很开放。相反,您应该使用预准备语句:
<?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();
?>
答案 1 :(得分:0)