搜索两列并回显结果以查找范围


Search two columns and echo results for a range

我有一个表单textfieldsubmit。当输入一个数字(例如102)并提交时,它会搜索数据库并查看两列(smin & &;smax)。在文本框中键入的数字将是10个范围中的一个。然后,它将找到它等于的范围(102将在第三个范围- 查看下面),然后为该范围回显信息。

DB表

id  smin  smax
1   50    80
2   81    95
3   96    103 

我就是不知道该做什么。原因是,我有超过10个范围,然后告诉它返回一些关于范围的文本,这是我从未做过的。

$stmt= $db->prepare('SELECT * FROM ranges WHERE 
smin >=100 AND smax <= 119');

当然这不起作用,也不是我想做的,因为我有db…我想让它到数据库中搜索这两列,确定它等于哪一行。

数据库设置:

create table ranges
(   id int auto_increment primary key,
    smin int not null,
    smax int not null
);
insert ranges (smin,smax) values (32,49),(50,80),(81,95),(96,103),(104,115); -- etc

PDO with Prepare and Bind

问题被标记为pdo

<?php
    $theNum=102;    // get from user, this is hard-coded
    try {
        $dbh = new PDO('mysql:host=localhost;dbname=so_gibberish;charset=utf8', 'TheUser', 'ThePassword');
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $dbh->prepare('SELECT id,smin,smax from ranges 
            WHERE smin <= :theNum AND smax >= :theNum');
        $stmt->bindParam(':theNum', $theNum, PDO::PARAM_INT);
        $stmt->execute();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // one row we hope
            $data = "id: ".$row['id'] . ", smin: " . $row['smin'] . ", smax: " . $row['smax'] . "'n";
            print $data;
        }
        $stmt = null;
        // PDO closes connection at end of script
    } catch (PDOException $e) {
        echo 'PDO Exception: ' . $e->getMessage();
        exit();
    }
?>
输出:

id: 4, smin: 96, smax: 103

假设AJAX将输入的值发送给服务器。那么它就像:

<?php
if(isset($_POST['HTMLnameAttribute'])){
  $numVal = $_POST['HTMLnameAttribute'];
  $stmt = $db->prepare("SELECT * FROM ranges WHERE smin >= $numuVal && smax <= $numVal");
  $stmt->execute();
  if($stmt->rowCount() > 0){
    while($r = $stmt->fetchObject()){
      // $r is Object - access like $r->id; $r->smin; $r->smax;
    }
  }
}
?>

以上代码假设您已经有数据库连接。