the following is an example showing the code and queries needed to accomplish this task -
<?php
// initialization
// these settings should be in the php.ini on your system -
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Start the session
session_start();
// fake a logged in user
$_SESSION['user_id'] = 1;
// insure the current visitor is logged in
if(!isset($_SESSION['user_id']))
{
// handle a non-logged in user here...
header('location:index.php');
die; // stop code execution
}
// use exceptions for database statement errors and only handle the exception for user recoverable errors
// based on the sql syntax error posted, you ARE using exceptions for database statement errors. do yourself a favor and remove all the existing database error handling logic since it is no longer being used and is just cluttering up your code.
require 'pdo_connection.php';
$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors
// post method form processing
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
// input(s) - gname, this should be the selected user's id - e.g. gid or similar
// trim all the input data at once
$post = array_map('trim',$_POST); // if any input is an array, use a recursive trim call-back function here instead of php's trim
// validate the input data
// the selected user's id
if($post['gid'] === '')
{
$errors['gid'] = 'You must select a user';
}
else if($post['gid'] == $_SESSION['user_id'])
{
$errors['gid'] = 'You cannot select yourself';
}
else
{
// find if the selected user exists
$sql = "SELECT COUNT(*) FROM users WHERE id=?";
$stmt=$pdo->prepare($sql);
$stmt->execute([ $post['gid'] ]);
if(!$stmt->fetchColumn())
{
// if you see this error, it is either due to a programming mistake or someone submitting data values that are not from your code
$errors['gid'] = 'The selected user does not exist';
}
}
// if no errors, use the data
if(empty($errors))
{
// since it is doubtful the OP will change what they are doing, the following updates the value in the token column
// start transaction
$pdo->beginTransaction();
// subtract 1 token from the current user, if they have enough tokens
$sql = "UPDATE users SET token=token-1 WHERE token > 0 AND id=?";
$stmt=$pdo->prepare($sql);
$stmt->execute([ $_SESSION['user_id'] ]);
if($stmt->rowCount())
{
// the UPDATE query affected the row, token was > 0
// add 1 token to the recipient user
$sql = "UPDATE users SET token=token+1 WHERE id=?";
$stmt=$pdo->prepare($sql);
$stmt->execute([ $post['gid'] ]);
}
else
{
// the UPDATE query didn't affect the row, token is not > 0
$errors['token'] = "You don't have enough tokens";
}
// if you are here, no database errors/exceptions occurred, commit the transaction
$pdo->commit();
}
// if no errors, success
if(empty($errors))
{
$_SESSION['success_message'] = "You have successfully gifted a token";
die(header("Refresh:0"));
}
}
// get method business logic - get/produce data needed to display the page
$sql = "SELECT id, username FROM users ORDER BY username";
$stmt = $pdo->query($sql);
$all_user_data = $stmt->fetchAll();
// html document starts here...
?>
<?php
// test for, display, and clear any success message
if(!empty($_SESSION['success_message']))
{
echo "<p>{$_SESSION['success_message']}</p>";
unset($_SESSION['success_message']);
}
?>
<?php
// test for and display any errors
if(!empty($errors))
{
echo '<p>'.implode('<br>',$errors).'</p>';
}
?>
<?php
// display the form, repopulating form fields using any data in $post
?>
<form method='post'>
<select name='gid'>
<option value=''>Select a user</option>
<option value='234'>An invalid user</option>
<?php
foreach($all_user_data as $row)
{
$sel = isset($post['gid']) && $post['gid'] == $row['id'] ? 'selected' : '';
echo "<option value='{$row['id']}' $sel>{$row['username']}</option>";
}
?>
</select><br>
<input type='submit'>
</form>
this code renamed the session variable, because many things have 'id's, what exactly is the id stored in the session?
uses the much simpler and more modern PDO database extension.