0

I want to check whether an IP exist in a database after it has been generated.My code works but it takes a whole 6 seconds to execute the following function 50,000 times. I am on PHP 7 (MySQL 5.7.11) but i will use mariadb in production.

How can i modify the sql to make it execute faster

function ip_exist ($db,$ipv6_address) {

    $db->query("SELECT ipv6 FROM tbl_ipv6 WHERE ipv6 = inet6_aton(:ip)  LIMIT 1");
    $db->bind(':ip', $ipv6_address);
    $db->single();
    if ($db->rowCount() > 0) {
        return true;
    } 
    return false;
}

SQL

    CREATE TABLE `tbl_ipv6` (
      `ipv6` varbinary(16) NOT NULL,
      `email_id` varchar(255) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `tbl_ipv6`
  ADD PRIMARY KEY (`ipv6`);

No of rows in table : 4

Update 2 Query becomes the following (Thanks Bernd Buffen)

$db->query("SELECT ipv6 FROM tbl_ipv6 WHERE ipv6 = inet6_aton(:ip)");
1
  • Since you're just checking that an IP address exists you can also just do SELECT 1 FROM ... and check whether the result is true/false - this will have much less of an effect than adding the appropriate index though. Commented May 20, 2016 at 9:47

1 Answer 1

1

Create a INDEX on this Column:

ALTER TABLE tbl_ipv6
ADD KEY (ipv6);

now try again:

if the ips are unique you can set the key unique.

Sign up to request clarification or add additional context in comments.

4 Comments

@user2650277 a primary key is an index - you don't need both
tell a bit more. Which engine you are using. how many records in the table, please post the output from SHOW CREATE TABLE tbl_ipv6; and which Version you using
and please post also the output from : EXPLAIN SELECT ipv6 FROM tbl_ipv6 WHERE ipv6 = inet6_aton(:ip) LIMIT 1. NOTE: if you have the Primary key on ipv6 or a unique key you dont use LIMIT 1. there is only one record
@BerndBuffen i added your changes but improvement isn't significant...check post for updates

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.