Select logged in user's ID using PDO

2020-05-09 20:09发布

问题:

I am new to using PDO and was wondering how I would select the logged in user's id from my phpMyAdmin database.

My initialization file is...

session_start();

$_SESSION['user_id'] = 1;

$db = new PDO('mysql:host=localhost;dbname=project', 'root', '');

Here is my users table layout:

回答1:

I'm assuming you want to get the users info where their id is the same as user_id

You might do something like this;

$query = $db->prepare('SELECT * FROM table WHERE id=:id');
//using bindParam helps prevent SQL Injection
$query->bindParam(':id', $_SESSION['user_id']);
$query->execute();
//$results is now an associative array with the result
$result = $query->fetch(PDO::FETCH_ASSOC);

I wasn't sure how user_id is set so I just used bindParam just in case.