I’m building a web application that tracks territory statistics for players in a game-like system. I need to update numeric values in my database but I’m running into problems with my SQL query.
My database table called users has these columns:
- forest_total
- town_total
- cave_total
- sky_total
I want users to pick a territory type from a dropdown, then my PHP code should update the right column. Here’s what I tried:
// Build column name from form input
$territory = $_POST['territory_type'] . '_total';
if (!isset($_POST['subtract']))
{
$operation = 'INCREASED';
try
{
$statement = 'UPDATE users SET
`:territory` = `:territory` + :amount WHERE user_id = :user_id';
$cmd = $database->prepare($statement);
$cmd->bindValue(':territory', $territory);
$cmd->bindValue(':amount', $_POST['amount']);
$cmd->bindValue(':user_id', $_POST['user_id']);
$cmd->execute();
}
catch (PDOException $ex)
{
$message = 'Database update failed: ' . $ex->getMessage();
include './error_page.php';
exit();
}
}
But I get this error message:
Database update failed: SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘‘town_total’’ in ‘field list’
When I remove the backticks around the placeholder I get a different syntax error. How can I make this work with dynamic column names?