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

Display data to Logged In User – PHP

I am creating a page that will display the login history. My code currently displays all logs and should only display the log history from the logged-in user.

Database -> Logs:

log_id | user_email | ip_address | time 
-------+------------+------------+-----
  1    | ml@a.com   | 123.13.13  | 1:30 

LogHistory.php page:

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

<?php
    $stmt = $dbh->prepare("SELECT * FROM Logs ORDER BY log_id ASC");
    $stmt->execute();
    if ($stmt->rowCount() == 0) {
        echo 'Log history are empty.';
    } else {
        // Data we collected from the registered user
    }
?>

I have tried this code:

<?php
$LoggedInUser = $_SESSION['user'];
$stmt = $dbh->prepare("SELECT * FROM Logs WHERE user_email = $LoggedInUser ORDER BY log_id ASC");
$stmt->execute();
if ($stmt->rowCount() == 0) {
    echo 'Log history are empty.';
} else {
    // Data we collected from the registered user
}
?>

With the above code I get this error message:

PHP Fatal error:  Uncaught PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':user@example.com ORDER BY log_id ASC'

>Solution :

You just need to use parameters with prepared statements

<?php
    $LoggedInUser = $_SESSION['user'];
    $stmt = $dbh->prepare("SELECT * FROM Logs WHERE user_email = ? ORDER BY log_id ASC");
    $stmt->execute([$LoggedInUser]);
    if ($stmt->rowCount() == 0) {
        echo 'Log history are empty.';
    } else {
        // Data we collected from the registered user
    }
?>

Here live PHP code

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