I have a database where I store data of users and devices. Every user has a list of devices. When the user logs into his account the php
code below generates a list of the users devices:
$query_user="SELECT * FROM devices WHERE users_id = '".$user_id."'";
$result = mysqli_query($db, $query_user);
// generating device list and ON and OFF device links
while($row = $result->fetch_assoc())
{
echo "<br><p>". $row["device"] ."</p><a href=on.php?data=" . $row["device"] . ">ON</a><br><a href=off.php?data=" . $row["device"] . ">OFF</a><br>";
}
The code also generates a ON
and OFF
link so the user can manipulate his devices. When the user click for example ON
then the following URL
is passed to the browser:
https://.../on.php?data=device23
The part of the on.php
code that handles the URL data:
if(isset($_GET["data"]))
{
$device_name = $_GET["data"];
}
$query_user="UPDATE devices SET status='ON' WHERE device = '".$device_name."'";
mysqli_query($db, $query_user);
So my problem here is that this approach is vulnerable to SQL injection, for example someone can type:
https://.../on.php?data=device17
in the browser and turn the device17
on.
My question is how the generate ON
and OFF
links for a list of devices and pass the data safe to the on.php
and off.php
files.
EDIT:
My main problem here is how to generate ON and OFF links for every users device (every user has a different number of devices). When the user clicks the ON link of for example device23 (or any other device, initially I don't know the device name, I am getting the device names from the first db query) I have to pass the device name to the on.php file so it can preform the SQL query that updates the device status.