0

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 in 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>

1 Answer 1

1

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., triming the input, etc...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.