简体   繁体   中英

MySQL Query from HTML form - can an input use wildcards?

I've had a look, and while I've seen lots of explanations for using wildcards in the original PHP, I've not found anything to help me when the user input wants to use wildcards. I am very new to PHP and MYSQL. Which symbol should be used?

Basically, the user requests data from the MYSQL database for a given grade, which can be a simple number or a number followed by a letter, or a plus sign. I'd like them to be able to request specifically 6a (which works fine) or 6 followed by a wildcard to return 6a, 6a+, 6b etc (which I don't know how to do).

For further detail:

I have the following form:

<form name="gradereturn" method="POST" action="gradequery.php">
<input type="text" name="Grade" value="Grade">
<input type="submit" name="Submit1" value="Retrieve">

and PHP:

<?php
$grade = $_POST['Grade'];
if (isset($_POST['Submit1'])) {
    mysql_connect("localhost", "**details**", "**details**") or die(mysql_error());
    mysql_select_db("**details**") or die(mysql_error());
    $result = mysql_query("SELECT * FROM routes WHERE Grade='$grade'") or die(mysql_error());  
    $row = mysql_fetch_array( $result );
    echo "Line - Colour - Grade<br />";
    while($row = mysql_fetch_array($result)){
        echo $row['Line']. " - ". $row['Colour']. " - ". $row['Grade'];
        echo "<br />";
    }
}
else print ("Please enter your required grade above");
?>

Thank you in advance for any help.

Use LIKE and make sure you escape $grade as well:

$grade = mysql_real_escape_string($grade);
$sql = "SELECT * FROM routes WHERE Grade LIKE '{$grade}'";
$result = mysql_query($sql);

They can then specify 6 or 6% or 6? etc.

You will want to use the LIKE command.

$result = mysql_query("SELECT * FROM routes WHERE Grade LIKE '$grade%'")

This tells SQL to find all entries in routes where Grade starts with $grade .

For more information on LIKE - MySQL Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM