0

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?

Redhawk
  • 103
  • 2

1 Answers1

4

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?

Paul
  • 892
  • 2
  • 8
  • 15
  • Hey Paul, thank you for your answer. Unfortunately this doesn't work for me. I'm certain that i've done something wrong somewhere. If i, instead of ".$_POST['id']." insert a ID number the code does work. Weird. – Redhawk May 13 '18 at 09:45
  • 1
    Could you `var_dump($_POST['id'])` before executing the query to make sure your id is actually in there? – Paul May 13 '18 at 09:49
  • I tried that and `var_dump` returned `string(16)`. What could that mean? I don't have any device with id 16. – Redhawk May 13 '18 at 10:08
  • Then we just found the problem. How do you retrieve the devices (probably how does your query look like?) so you can display them like ``? – Paul May 13 '18 at 10:23
  • 1
    I got it working now! Changed the value of `` from `value=""` to `value="{$row['id']}"` and it worked together with your first answer, thank you! – Redhawk May 13 '18 at 10:44