Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php – Updating data in database base on id?

I am working on a project that takes students attendance in class and I want to update the database data through PHP whilst running a SQL function of UPDATE, but I want to be able to update it base on the id of the data.

This is the code that I am working with at the moment.

<?php

require_once './dba.php';

$status = "";

if(isset($_POST['time_in'])) {

    $query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";

    $d = $conn->prepare($query);

    $d->execute();     

} elseif(isset($_POST['time_out'])) {
    $query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = ? ";

    $d = $conn->prepare($query);

    $d->execute();     
} else {
    $status = "Can't time in!";
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use $conn->lastInsertId() to get the ID that was assigned when they clocked in. Save that in a session variable and use it when they clock out.

<?php

require_once './dba.php';

$status = "";

if(isset($_POST['time_in'])) {
    $query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
    $d = $conn->prepare($query);
    $d->execute();     
    $_SESSION['clock_id'] = $conn->lastInsertId();
} elseif(isset($_POST['time_out'])) {
    if (!isset($_SESSION['clock_id'])) {
      $status = "You need to clock in first!";
    } else {
      $query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
      $d = $conn->prepare($query);
      $d->execute(['id' => $_SESSION['clock_id']]);   
    }
} else {
    $status = "Can't time in!";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading