I have this page with a login system, and a point system. Everytime a user completes a task, he or she will recieve +5 points. Now, how do I UPDATE the value of point in my database of the currently logged in user?
I know I can do UPDATE table SET point=+5 WHERE id=usersid
, but I can't figure out how to get the id of the currently logged in user? The login and register system is written with PDO.
Here is my full code of config.php:
<?php
$username = "root";
$password = "";
$host = "localhost";
$dbname = "login";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Kunne ikke forbinde til databasen: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
And here is my reward.php, which is not working:
<?php
require('config.php');
$userId = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
$query = "UPDATE users SET point=point+5";
//Yes, i do realize that i need a WHERE to avoid updating the whole table.
echo("$userId's point er opdateret.");
?>
The echo part in reward.php echoes the logged in users username just fine, but the database is just not updating. No errors either.
Huge thanks for the answers guys, much appreciated!
You can edit a certain user's points only by knowing their user ID (or some other value unique to that user).
As you made clear in the comments, you save the user ID in a session. What you have to keep in mind is to include your config.php
in every page where a user's points are updated.
require 'config.php';
The next thing you need to know is that you can get the user's ID back from the session using PHP's global session variable.
$userId = $_SESSION['user_id']; // Note: this could have some other name in your case
Now that we have the user ID we can start updating that user's points. I don't know what your method of communicating with the database is so I left that up to you.
Now we'll want to update the users points.
$query = "UPDATE users SET point=point+5 WHERE user_id='".$userId."' LIMIT 1";
That's all there is to it.