简体   繁体   中英

Can someone tell me what is wrong with this MySQL query?

This Query I am using is returning ALL data in this table. I want to search for an EXACT ID number and have it return ONLY that result. Also, how can I implement mysql_real_escape_string() here?

thanks!

$term = $_POST['term'];

$sql = mysql_query("select * FROM patient WHERE id_number LIKE '%$term%'");

while ($row = mysql_fetch_array($sql)){

    echo 'ID: '                 .$row['id'];
    echo '<br/> First Name: '   .$row['first_name'];
    echo '<br/> Last Name: '    .$row['last_name'];
    echo '<br/> Business Name: '    .$row['business_name'];
    echo '<br/> ID Number: '    .$row['id_number'];
    echo '<br/><br/>';
} 
?>

Use:

$query = sprintf("SELECT p.*
                    FROM PATIENT p
                   WHERE p.id_number = '%s'",
                  mysql_real_escape_string($_POST['term']));

$result = mysql_query($query)

while($row = mysql_fetch_array($sql)) { ...

Reference:

If you're looking for only one row, you really shouldn't be using LIKE , but = , eg:

$sql = mysql_query( sprintf("select * FROM patient WHERE id_number='%s'", mysql_real_escape_string( $_POST['term'] ) ) );

The above should return only one row if: 1) id_number is unique in patient , and 2) $term actually corresponds to a value of id_number .

Hopefully this also answers your question about how to use mysql_real_escape_string() , too!

You would use mysql_real_escape_string() on user input, which in this case is $_POST['term'] .

If you want an exact match, then you shouldn't use LIKE :

$term = mysql_real_escape_string($_POST['term']);

$sql = mysql_query("select * FROM patient WHERE id_number = '$term'");

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