user1476394
user1476394

Reputation: 347

MySQL php INSERT INTO taking very very long time

I want to insert 0 to 10000000 (10 million) of primary keys into my table.

My table is as follow:

p_key-->      (INT[10]) AUTO_INCREMENT PRIMARY KEY UNIQUE
hash_value--> (SMALLINT)
req_count--> (SMALLINT)

only adding 100 records is taking 11 seconds for 500 records it is giving 30 second timeout has been crossed.(wamp server localhost php mysql)

for ($i=0;$i<100;$i++){
    $query='INSERT INTO hash_table (hash_value, req_count) VALUES (0,0)';
    $result=$con->query($query);
    if(!$result){
        echo ("Error message:".$con->error." \n");
        exit();
    }
  }

Am I doing something terribly wrong.

Upvotes: 2

Views: 793

Answers (2)

Kickstart
Kickstart

Reputation: 21513

Another option, doing it in a single SQL statement:-

INSERT INTO hash_table (hash_value, req_count)
SELECT 0, 0
FROM
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)units,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)tens,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)hundreds,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)thousands,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)tensthousands,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)hundredthousands,
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)millions,
(SELECT 0 i UNION SELECT 1)tensmillions
WHERE (units.i +
        tens.i * 10 +
        hundreds.i * 100 +
        thousands.i * 1000 +
        tensthousands.i * 10000 +
        hundredthousands.i * 100000 +
        millions.i * 1000000 +
        tensmillions.i * 10000000) BETWEEN 0 AND 10000000

Upvotes: 1

Pvb
Pvb

Reputation: 436

You should insert more then one records at one SQL query.

For example:

$values='';

for ($i=0;$i<100;$i++){
    $values.='(0,0),';
}

$values=substr($values,0,-1);

$query='INSERT INTO hash_table (hash_value, req_count) VALUES '.$values;
$result=$con->query($query);
if(!$result){
    echo ("Error message:".$con->error." \n");
    exit();
}

Upvotes: 5

Related Questions