Button always returning the last ID

Asked

Viewed 29 times

0

I am making a system, I need it to check the ID of the button that was clicked on the table and perform the action, however it is always picking up the last id, someone knows what can be?

if(isset($_SESSION["mensagemreset1"])):
    print $_SESSION["mensagemreset1"];
    unset($_SESSION["mensagemreset1"]);
endif;

$id = $_SESSION['idlogin'];

$sql = "SELECT * FROM `char` WHERE account_id='$id'";
$sql = $pdo->query($sql);

foreach ($sql->fetchAll() as $row) {

    echo "<tr>";
    echo "<td>".$row['name']."</td>";
    echo "<td>".$row['base_level']."/".$row['job_level']."</td>";
    echo "<td>".$row['class']."</td>";
    echo "<td>".$row['guild_id']."</td>";
    echo "<td><button type='submit' class='btn btn-success btn-sm'>Resetar Aparência</button> <button type='button' class='btn btn-info btn-sm'>Resetar Posição<br></button></td>";

    echo "<td><input type='hidden' name='id' value=".$row['char_id']."></td>";

    echo "</tr>";
}

resetar_appearance.php:

include 'config.php';
require 'Usuario.class.php';

global $pdo;
global $char_id;

echo  $_POST['id'];

$statement = $pdo->prepare("UPDATE `char` SET hair=1, hair_color=1, clothes_color=1 WHERE char_id = '$char_id'");

$statement->execute();
//header("Location: inicio.php?pg=meuspersonagens");
$_SESSION['mensagemreset1'] = "<div class='sufee-alert alert with-close alert-success alert-dismissible fade show'>
  Aparência do personagem resetada com sucesso.
  <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
    <span aria-hidden='true'>&times;</span>
  </button>
  </div>";

I put echo only to test, but it always returns me the last ID.

  • Check your HTML tags closes before and after your foreach, also check via element inspector if there is no php error being printing in the middle of your html;

1 answer

0


Although you have a button like submit on each line there is no form in the code presented. Most likely you forgot to add this part to the question, otherwise your code would not call resetar_aparência.php.

Disregarding this detail, the problem is that the buttons Resetar Aparência are of the type Submit will always send the form. So add a form (tag form) for each row of your table. With this, the button will always be specific to a single form.

foreach ($sql->fetchAll() as $row) {
    echo "<tr><form method=\"POST\" action=\"resetar_aparência.php\">";
    (...)
    echo "</form></tr>";
}
  • No need to thank, @Rafaelrenan. Just accept / make up vote from answer ;) This comment will probably be deleted...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.