简体   繁体   中英

Cannot insert data into MySQL database via PHP

I'm setting up a dashboard and need users to be able to see their session history for security purposes. So I decided to create a database and use PHP to insert the session_id() , CURRENT_TIMESTAMP and some other variables into the table, but for some reason PHP and/or MySQL is not able to INSERT the values into the database. I'm able to read and display data from that same database, but I'm not able to INSERT or UPDATE the data.

The server I'm working on is running Apache 2, PHP 7, and MySQL 5. I've tried inserting and updating data in the past (and on other servers) but I always run into this problem.

$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");
    }

I expect to see a new row in the database each time a user logs in, but I keep getting this error message Error code: , which doesn't tell me anything.

Session ID is a string, so you'll need to add a single quote around $session_id to your SQL on the VALUES side like this:

$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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM