How to echo button with onclick function using foreach and condition in php?

Expect:

Select data from my SQL. Foreach to echo data and the button. When the data is null, display the “join” button with onclick function. When the data is “joined”, hide the “join”button with onclick function, display the “result” button with onclick function.

Result:

Cannot hide the “join”button with onclick function, display the “result” button with onclick function.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
    
         $servername = "localhost";
         $username = "root";
         $password = "";
         $dbname = "battle";
        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $stmt = $conn->prepare("SELECT * FROM battleRecord Group by id");
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
                                        
            foreach ($stmt->fetchAll() as $row) {
              if ($row['participation'] == 'joined') {
                $displayJoin = 'none';
                $displayResult = 'block';
            } else {
                $displayJoin = 'block';
                $displayResult = 'none';
            }
               ?>

              <tr>
              <td style='width:150px;border:1px solid black;'>                                
              <p><?php echo $row['id']?></p>
            
              </td>  
              <td style='width:150px;border:1px solid black;'>                                
              <button style="display:<?php echo $displayJoin ?>" id="joinBattle" onclick="joinBattle(<?php echo htmlspecialchars($row['id']) ?>)">joinbattle</button>
              
              <button style="display:<?php echo $displayResult ?>" id="checkResult" onclick="checkResult(<?php echo htmlspecialchars($row['result']) ?>)">result</button>
              
              </td>  
              </tr>
                                                
              <?PHP

                }
                } catch (PDOException $e) {
                  echo "Error: " . $e->getMessage();
                }
                  $conn = null;
                  
                   ?>

   
    </body>
    </html>

Result and Mysql

MySQL part 1

MySQL part 2

Result

View Source

Answer

You never set $displayJoin to block. Use this:

if ($row['participation'] == 'joined') {
    $displayJoin = 'none';
    $displayResult = 'block';
} else {
    $displayJoin = 'block';
    $displayResult = 'none';
}

Leave a Reply

Your email address will not be published. Required fields are marked *