I wrote some PHP code that shows all 'cars' a user has in his garage. It shows the model, the worth and a sell button, but I can't seem to fix the sell button. The sell button appears in every row in the table together with the model and worth (waarde). I want that if you press the sell button, the right car gets sold and deleted from the database. But right now, it doesn't matter which one you press, it sells all the cars. I think I am just putting the code for the selling of the cars at the wrong place, so can someone help me figure this out?
Code:
<?php
include "notLoggedIn.php";
$username = $_SESSION['username'];
$globalstmt = $pdo->prepare("SELECT id from users where gebruikersnaam = :username");
$globalstmt->execute(['username' => $username]);
$globalrow = $globalstmt->fetch();
$globalid = $globalrow['id'];
$stmt = $pdo->prepare("SELECT auto_id FROM garage WHERE user_id = :globalid");
$stmt->execute(['globalid' => $globalid]);
$rows = $stmt->fetchAll();
if (count($rows) == 0) {
echo "Je hebt nog geen auto's in je garage.<br /><a href='auto_stelen.php'>Druk hier om een auto te proberen stelen!</a>";
} else {
echo "<table width='300px''>
<tr>
<th>Garage</th>
</tr>
<tr>
<td><b>Model</b></td>
<td><b>Waarde</b></td>
</tr>
<form method='post'>
";
foreach ($rows as $row) {
$autos = $row['auto_id'];
$stmt = $pdo->prepare("SELECT * FROM autos WHERE id = :autos");
$stmt->execute(['autos' => $autos]);
$row = $stmt->fetch();
echo "
<tr>
<td>" . $row['model'] . "</td>
<td>€" . number_format($row['waarde'], 0, ',', '.') . "</td>
<td><input type='submit' name='sell' value='Verkopen' /></td>
</tr>";
}
echo "
</form>
</table>";
}
if (isset($_POST['sell'])) {
$stmt = $pdo->prepare("SELECT * FROM garage WHERE user_id = :globalid");
$stmt->execute(['globalid' => $globalid]);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$autos = $row['auto_id'];
$stmt = $pdo->prepare("SELECT * FROM autos WHERE id = :autos");
$stmt->execute(['autos' => $autos]);
$row = $stmt->fetch();
$waarde = $row['waarde'];
$stmt = $pdo->prepare("UPDATE users SET cashgeld = cashgeld + :waarde WHERE gebruikersnaam = :username");
$stmt->execute([
'waarde' => $waarde,
'username' => $username
]);
$stmt = $pdo->prepare("DELETE FROM garage WHERE auto_id = :autos");
$stmt->execute(['autos' => $autos]);
header("Refresh: 0");
}
}
?>
The page currently looks like this