GregHBushnell GregHBushnell - 2 months ago 4
HTML Question

php repeating submit buttons different values

Hi using the code below i generate a table with a submit button for each row

function GetPlayer($link){
if (isset($_SESSION['username'])) {
$x = 0;
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
$result = mysqli_query($link,$sql);

while($row = mysqli_fetch_assoc($result)){
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
echo ("<tr>");
echo ("<th>".$row['username']." </th>");
echo ("<th>Level: ".$row['Level']." </th>");
echo ("<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>");
echo ("<th>Win Chance: ");
echo CalculateWinChance($link,$row['Defence']);
echo ("<th><input type ='submit' name = 'Attack_Btn' value ='Attack'></th>");
echo ("</tr>");
}
}
}
}


now i need this button to call 2 functions and passing in certain values to these functions

an example of a button that is not generated this way but does use the same functions is below

if(isset($_POST['Dummy_Btn'])){
$winChance = CalculateWinChance($link,5);
Train($link,1,1,$winChance);
}


is calls two functions passing in 5 to return a different value that then gets passed into another function

how am i able to get the data such as $row['Attack'] and it be different from each of the other generated submit buttons.

ive been reading about ajax could this be used in this situation?

Answer

The best way to go about doing this is as Leeish says.

Create a hidden field in the form. Also you can reduce the amount of echos you use by assigning them to a variable and echoing that variable.

    function GetPlayer($link){
    if (isset($_SESSION['username'])) {
    $x = 0; 
        $sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
        $result = mysqli_query($link,$sql);

        while($row = mysqli_fetch_assoc($result)){
            if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
                $toEcho  = "<tr>";
                $toEcho .= "<th>".$row['username']." </th>";
                $toEcho .= "<th>Level: ".$row['Level']." </th>";
                $toEcho .= "<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>";
                $toEcho .= "<th>Win Chance: ";
                $toEcho .= CalculateWinChance($link,$row['Defence'];
                $toEcho .= "<input type='hidden' name='Hiiden1' value='YOUR NUMBER' />";
                $toEcho .= "<th><input type ='submit' name = 'Attack_Btn' value ='Attack'></th>";
                $toEcho .= "</tr>";

                echo $$toEcho;
            }
        }
    }
}

Then you can get the value of the hidden variable by..

if(isset($_POST['Dummy_Btn'])){

    $hidden = $_POST["hidden1"];

    $winChance = CalculateWinChance($link,5);
    Train($link,1,1,$winChance);
}

And now you can use it as you wish.