Skip to content
Advertisement

PHP Prepared MySQL UPDATE Statement with Variable inside of a string

I am trying to include a variable inside of a string in an update query but seem to be having trouble. I am just now updating all of my old websites to use prepared statements so I am not that familiar with them yet. What do I need to do to get the string and variable connected in the query.

$insert = $pdo->prepare("INSERT INTO trees (name, unit) VALUES(:name, :unit)");
$insert->execute([
    'name' => $name,
    'unit' => $unit
]);
$insertid = $pdo->lastInsertId();
// THIS LINE SPECIFICALLY IS WHERE MY PROBLEM IS    vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
$update = $pdo->prepare("UPDATE trees SET filename='tree_".$insertid."_:file_name' WHERE id=:insertid");
$update->execute([
    'file_name' => $file_name,
    'insertid' => $insertid
]);

I have tried without the single quotes, with the single quotes before the :file_name. But all I seem to get is errors. Any help would be greatly appreciated!

Advertisement

Answer

You want concat(), and query parameters rather than string concatenation:

UPDATE trees 
SET filename = CONCAT('tree_', :insertid, '_', :file_name) 
WHERE id = :insertid

Actually, CONCAT_WS() comes handy here:

UPDATE trees 
SET filename = CONCAT_WS('_', 'tree', :insertid, :file_name) 
WHERE id = :insertid
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement