I am using Ajax to select an option from a dropdown menu which then places the option selected into a mysql query as the variable
query looks like this:
select * from table where VARIABLE = 'Yes';
http://sqlfiddle.com/#!9/21afac/3
Here is an SQLfiddle with some example data and i have used nuts in the query to give an idea of how im trying to get the result outcome where nut is the variable replaced by q in the below code.
In the fiddle Nuts returns just 1 result whereas in my actual DB it returns all the rows when i replace Nuts with '".$q."' in my query
The test.php file that im using where the variable is being defined by q and in the dev console it shows q returning as the dropdown option selected.
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','user','password!','DB');
if (!$con) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM db.table WHERE '".$q."' = 'Yes' ";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Product</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
my test.html side with the dropdown
<html>
<head>
<script>
function allerg(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","test.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="allerg(this.value)">
<option value="">Select a person:</option>
<option value="Milk">Milk</option>
<option value="Wheat">Wheat</option>
<option value="Egg">Egg</option>
<option value="Nuts">Nuts</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>