Redhawk
Redhawk

Reputation: 103

Sending $row['id'] through a form to another PHP using a button

I'm trying to create a page that can toggle devices on and off, a smart home kind of thing.

The code looks as follows:

<form method="post" action="toggle.php">
        <input type="hidden" name="id" value="<?php echo {$row['id']};?>"/>
        <button type="submit" name="on" id="on" class="btn btn-success">On</button>
        <button type="submit" name="off" id="off" class="btn btn-danger">Off</button>
</form>

This is the form that sends either "on" or "off" to toggle.php.

Toggle.php looks like this:

<?php 
include('devices.php');

if (isset($_POST["on"])){

        mysqli_query($mysqli,"UPDATE devices SET status = 'On' WHERE id = '$row['id']'");       
}
if(isset($_POST["off"])){

        mysqli_query($mysqli,"UPDATE devices SET status = 'Off' WHERE id = '$row['id']'");

}
?>

My question is: how do i get what's in $row['id'] in the form to get sent to toggle.php and then be used to update the status of the device?

Upvotes: 0

Views: 284

Answers (1)

Paul
Paul

Reputation: 942

You can access the data you are posting to the toggle.php with the superglobal $_POST, just as you did with $_POST['off'] for example.

mysqli_query($mysqli,"UPDATE devices SET status = 'On' WHERE id = '".$_POST['id']."'"); 

Quick note: Your code is vulnerable to SQL injections, you might want to learn about them here: How can I prevent SQL injection in PHP?

Upvotes: 4

Related Questions