mysql,其中inet_aton喜欢%...%

时间:2016-12-26 09:41:11

标签: mysql search ip where

在我的数据库中,我使用INET_ATON

存储IP(ipv4)
<?php
$ip = mysqli_real_escape_string( $con, $_SERVER[ 'REMOTE_ADDR' ] );
mysqli_query( $con, "INSERT INTO table ( ip ) VALUES ( INET_ATON( '$ip' ) )" );

然后,搜索正常的ip&#34;我做了以下

SELECT *  FROM table WHERE ip = INET_ATON ('31.165.84.4')

但是我怎样才能只搜索ip的一部分?例如:

SELECT *  FROM table WHERE ip LIKE INET_ATON ('31.165.84') // not working
SELECT *  FROM table WHERE ip LIKE INET_ATON ('%31.165.84%') // not working

这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以使用反向功能INET_NTOA

并且您只有部分匹配('31 .165.84')(缺少最后一位数字)

require_once('config.php');
class myClass
{
    public $mysqli;
    public $res;
    function connect()
    {
        $database = new Database();

        $this->mysqli = new mysqli($database->db_host, $database->db_user, $database->db_pass, $database->db_table);
    }
    function cd($id)
    {
       ......
        }
    }        
}

class Cd extends myClass
{
    function cdname($id)
    {
        $get= new Scandiweb();
        $get->mysqli;

        $this->res = $get->mysqli->query("SELECT * FROM disk WHERE id=" . $id . "");
        if ($this->res->num_rows > 0) {
            .........
        }
    }
}

答案 1 :(得分:1)

您可以使用以下查询:

SELECT * 
FROM table 
WHERE ip 
  BETWEEN INET_ATON('31.165.84.0')
  AND INET_ATON('31.165.84.255');

<强>测试

SELECT  
if( INET_ATON('31.165.84.2') -- ip in Table
  BETWEEN INET_ATON('31.165.84.0') -- Min Addr.
  AND INET_ATON('31.165.84.255'),1,0); -- Max Addr.

<强>样品

mysql> SELECT
    -> if( INET_ATON('31.165.84.2')
    ->   BETWEEN INET_ATON('31.165.84.0')
    ->   AND INET_ATON('31.165.84.255'),1,0) as cmp;
+-----+
| cmp |
+-----+
|   1 |
+-----+
1 row in set (0,00 sec)

mysql>
mysql> SELECT
    -> if( INET_ATON('31.165.84.177')
    ->   BETWEEN INET_ATON('31.165.84.0')
    ->   AND INET_ATON('31.165.84.255'),1,0) as cmp;
+-----+
| cmp |
+-----+
|   1 |
+-----+
1 row in set (0,01 sec)

mysql>
mysql> SELECT
    -> if( INET_ATON('31.165.85.177')
    ->   BETWEEN INET_ATON('31.165.84.0')
    ->   AND INET_ATON('31.165.84.255'),1,0) as cmp;
+-----+
| cmp |
+-----+
|   0 |
+-----+
1 row in set (0,00 sec)

mysql>