简体   繁体   中英

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

You never set $displayJoin to block . Use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM