无法通过PHP将数据插入MySQL数据库

时间:2019-01-17 18:19:16

标签: php mysql database

我正在设置仪表板,出于安全目的,需要用户能够查看其会话历史记录。因此,我决定创建一个数据库,并使用PHP将session_id()CURRENT_TIMESTAMP和其他一些变量插入表中,但是由于某些原因,PHP和/或MySQL无法INSERT将值放入数据库。我可以从同一数据库读取和显示数据,但是无法INSERTUPDATE数据。

我正在使用的服务器正在运行Apache 2,PHP 7和MySQL5。我过去曾尝试插入和更新数据(以及在其他服务器上),但是我总是遇到这个问题。

$badge_number = $_SESSION['badge_number'];

$session_id = session_id();

$link = mysqli_connect('localhost', 'username', '*********', 'database');

   if (mysqli_connect_error()) {
        die("Cannot connect to database");
    }

    $query = "INSERT INTO `session_log` (`id`, `badge_number`, `session_id`, `session_start`, `session_end`, `session_length`) VALUES (NULL, $badge_number, $session_id, CURRENT_TIMESTAMP, NULL, 'regular')";

    $result = mysqli_query($link, $query);

    if (!$result) {
        die('Error code:' . mysqli_error());
    } else {
        header("Location: /overview?message=%3Cp%3E%3Cstrong%3ESuccess%21%3C/strong%3EYou%20have%20successfully%20logged%20in%20and%20inserted%20a%20new%20row%20in%20the%20session%20log%21%3C/p%3E&messagecolor=green&messageid=3942791098282");
    }

我希望每次用户登录时都会在数据库中看到一个新行,但是我不断收到此错误消息Error code:,但它什么也没告诉我。

1 个答案:

答案 0 :(得分:0)

会话ID是一个字符串,因此您需要在$session_id端在SQL的VALUES周围加上一个单引号,如下所示:

$badge_number = $_SESSION['badge_number'];

$session_id = session_id();

$link = mysqli_connect('localhost', 'username', '*********', 'database');

if (mysqli_connect_error()) {
    die("Cannot connect to database");
}

$query = "INSERT INTO `session_log` (`id`, `badge_number`, `session_id`, `session_start`, `session_end`, `session_length`) VALUES (NULL, $badge_number, '$session_id', CURRENT_TIMESTAMP, NULL, 'regular')";
//added single quotes around '$session_id' above on the VALUES side. 

$result = mysqli_query($link, $query);

if (!$result) {
    die('Error code:' . mysqli_error());
} else {
    header("Location: /overview?message=%3Cp%3E%3Cstrong%3ESuccess%21%3C/strong%3EYou%20have%20successfully%20logged%20in%20and%20inserted%20a%20new%20row%20in%20the%20session%20log%21%3C/p%3E&messagecolor=green&messageid=3942791098282");
}