Mysql Select with dynamic text field
I am trying to create a basic search function. I have a text field with an id of "npa" when I submit I would like the values placed i开发者_如何转开发n the npa field to be inserted in to the $searchroute mysql query.
I am VERY new to php so this has got me slightly stumped.
if ($_POST["submit"]) {
$searchroute = "SELECT * FROM destination_route as d WHERE d.destPrefix='npa'";
$results = mysql_query($searchroute);
$row = mysql_fetch_array($results);
print_r($row);
}
?>
<html>
<form name="query" id="showdid" action="" method="post" enctype="multipart/form-data" >
<input type="text" name="npa" id="npa" value="">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</html>
Since you're already using the mysql_*
functions, the example code below also uses them. However, you should abandon those functions and instead use PDO. That aside:
<?php
if (!empty($_POST['submit'])) {
if (!empty($_POST['npa'])) {
$searchroute = "SELECT *
FROM destination_route as d
WHERE d.destPrefix='".mysql_real_escape_string($_POST['npa'])."'";
$results = mysql_query($searchroute);
$row = mysql_fetch_array($results);
print_r($row);
}
}
?>
<html>
<form name="query" id="showdid" action="" method="post">
<input type="text" name="npa" id="npa" value="">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</html>
All I did was add some calls to empty (to avoid notices in case the variables haven't been created), escaped the data as it was sent to the database (very important, PDO makes this much easier too) and removed the enctype="multipart/form-data"
as it's not needed for your functionality (no files are being uploaded).
I've kept my modifications to a minimum to better show the basics of what needs to occur. There's much more you can do, such as perform additional sanitizing/validating of the input, e.g., trim
ing the input, etc...
精彩评论