开发者

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:

  • sprintf: http://php.net/manual/en/function.sprintf.php


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'");


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

$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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜