0

I currently am trying to learn a bit of HTML and PHP just for fun and am struggling to figure out how to use a button rather than a form in HTML to post to PHP.

This is one place I want to use it for a little ESP_8266 project.

if (isset($_POST['toggle_LED'])) {
    $sql = "SELECT * FROM LED_status;";
    $result   = mysqli_query($conn, $sql);
    $row  = mysqli_fetch_assoc($result);
    
    if($row['status'] == 1){
        $update = mysqli_query($conn, "UPDATE LED_status SET status = 0 WHERE id = 1;");        
    }       
    else{
        $update = mysqli_query($conn, "UPDATE LED_status SET status = 1 WHERE id = 1;");        
    }
}

Currently it toggles using this form:

<form method="post" id="LED" enctype="multipart/form-data">         
                <input id="submit_button" type="submit" class="button" name="toggle_LED" value="Toggle LED" />
            </form> 

What I would like to achieve is to use a button rather than a form so that the form can NOT resubmit and change the toggle status. I have tried using a "button onclick" and then having a <script> that names a function with what I want it to do within that function but I cant seem to get that to work either.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Always do a redirect after the post request – Your Common Sense Jun 17 '22 at 14:51
  • On JavaScript side you can disable the button after clicked. – Markus Zeller Jun 17 '22 at 14:53
  • What's the purpose of `SELECT * FROM LED_status`? I think `UPDATE LED_status SET status = case when status = 1 then 0 else 1 end WHERE id = 1` should be able to be used, or might even be a toggle function https://stackoverflow.com/questions/603835/mysql-simple-way-to-toggle-a-value-of-an-int-field – user3783243 Jun 17 '22 at 15:20
  • The `SELECT * FROM LED_status` is for my database that stores the status and ID of the LED that I switch on a wireless ESP_8266 board. Unless you mean to ask that for a different reason? – Pavlov Propagandalf Jun 17 '22 at 15:58
  • If you are only using the data for the update it is not needed. – user3783243 Jun 17 '22 at 16:21
  • Good to know, I still dont quite understand it but getting there. Do you have any suggestions regarding the HTML using a button rather than a form? – Pavlov Propagandalf Jun 17 '22 at 20:13

0 Answers0