如何在两个不同的按钮上执行相同的事件?

时间:2015-04-25 12:03:56

标签: php

我在下面有这段代码,假设当数据库中没有数据时它将不显示任何请求,并且当它们是数据库中的数据时,它将显示带有接受和拒绝按钮的请求。我应该如何编写代码以使接受和拒绝按钮执行某些操作?

<?php 

        $travelRequest = $user->userTravelRequest($userid);
        if(!$travelRequest){
            echo '<div class="requestbox">
                  <p> You have no request from others at the moment. </p>
                  </div>';
        }

        else {
            foreach($travelRequest as $request){

                echo '<div class= "requestbox">
                      <p>'. $request->trip_name.'</p>
                      <p>Organised by '.$request->username.'</p>';

        ?>

                      <form method="POST">
                      <div class = "AR-btn">
                      <input type="button" name="accept" value="Accept"/>
                      <input type="button" name="reject" value="Reject"/>
                      <p></p>
                      </div>
                      </form>
                      </div>

        <?php   

            }

        }
        ?>

3 个答案:

答案 0 :(得分:1)

使用type="submit"代替type="button",并为其指定相同名称。然后他们将提交表单,脚本可以从该参数的值中测试使用了哪个按钮。

<input type="submit" name="action" value="Accept"/>
<input type="submit" name="action" value="Reject"/>

然后用以下方法测试:

if (isset($_POST['action'])) {
    if ($_POST['action'] == 'Accept') {
        // Add to database
    } elseif ($_POST['action'] == 'Reject') {
        // Delete from database
    }
}

答案 1 :(得分:0)

试试这段代码: -

<?php
if (isset($_POST['accept']) && $_POST['accept'] == 'Accept' ) {
    // do what you want
     die("Accept is clicked");
} else if (isset($_POST['reject']) && $_POST['reject'] == 'Reject' ) {
    // do what you want
    die("Reject is clicked");
}
?>
<?php
        $travelRequest = $user->userTravelRequest($userid);
        if(!$travelRequest){
            echo '<div class="requestbox">
                  <p> You have no request from others at the moment. </p>
                  </div>';
        } else {

            foreach($travelRequest as $request){
                echo '<div class= "requestbox">
                      <p>'. $request->trip_name.'</p>
                      <p>Organised by '.$request->username.'</p>'; 

        ?>
              <form method="POST">
                  <div class = "AR-btn">
                      <input type="submit" name="accept" value="Accept"/>
                      <input type="submit" name="reject" value="Reject"/>
                  <p></p>
                  </div>
              </form>
          </div>
        <?php
            }
        }
?>

答案 2 :(得分:0)

试试这个逻辑......可以帮助你

$query = "select data from database";
    .
    .
    .


 $data = $row['data'];

    if($data){  // reject button when they is data in database
       echo '<input type="submit" name="action" value="Reject"/>';
    }
    else{ // viceversa
       echo '<input type="submit" name="action" value="Accept"/>';
    }