0

I have built a dropdown list using PHP to show all the Unique names in my Table. I want to use that dropdown list to then use the selected value to create a MySQL Statement Dynamically.

Select * From iot_sensors WHERE Sensor_ID = ['USE the DROPDOWN MENU TO SELECT A NAME']

$select2 = "SELECT DISTINCT Sensor_ID FROM iot_sensors;";
$result2 = mysqli_query($conn, $select2);
$counter2 = mysqli_num_rows($result2);

echo "<select name ='Sensor Names'>";
    while ($row = mysqli_fetch_assoc($result2)){
    echo "<option value ='".$row['Sensor_ID']."'>".$row['Sensor_ID']."   </option>";
}
    $dynamic_query = "SELECT * FROM iot_sensors WHERE Sensor_ID = ['option value']";
echo "</select>";

I understand usually if I had manually populated the dropdown menu all I would have to do is call the option value but here the option value is on there for HTML rendering purposes.

moe.Patel
  • 63
  • 1
  • 2
  • 9
  • If an answer solved your problem, consider accepting the answer. Here's how http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work then return here and do the same with the tick/checkmark till it turns green. This informs the community, a solution was found. Otherwise, others may think the question is still open and may want to post (more) answers. You'll earn points and others will be encouraged to help you. *Welcome to Stack!* – Jay Blanchard Mar 16 '17 at 19:15

1 Answers1

0

First some warnings:

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?


First, do not use names with spaces for HTML elements:

echo "<select name ='Sensor_Names'>";

Once selected and submitted (without knowing what your form method= is) the item will be in the $_REQUEST array:

$sensor_name = $_REQUEST['Sensor_Names'];
$dynamic_query = "SELECT * FROM iot_sensors WHERE Sensor_ID = '$sensor_name'";
Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119