Question: The following php script takes about 22 seconds to execute. Is it normal? If not what would cause it to execute slowly?

```
$conn = mysql_connect('localhost', 'root', '123');
mysql_select_db('mydb', $conn);
$time1 = time();
for ($i=1;$i<500;$i++) {
mysql_query("Insert into accounts(id, username, email, password) VALUES(\"$i\", \"$i\",\"$i\",NOW())");
}
print time() - $time1; // return ~22

```

Edit: Table structure:

```
CREATE TABLE IF NOT EXISTS `accounts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(20) NOT NULL,
  `status` varchar(10) DEFAULT 'pending',
  `email_newsletter_status` varchar(3) DEFAULT 'out',
  `email_type` varchar(4) DEFAULT 'text',
  `email_favorite_artists_status` varchar(3) DEFAULT 'out',
  `created_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7500 ;

```

This code is just to test insert speed. Using the Zend framework(insert method of Zend\_Db) I get a similar result, so I think it's relevant to mysql and not php code

Edit2: I know that there is much better ways to execute this query, but I want to know why this one is so slow.

Answer: 
Rather than run multiple insert statements, batch them up and execute it as one statement

```
 INSERT INTO example
  (example_id, name, value, other_value)
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

```

This will speed up your insert considerably
Try a single insert query:

```
$valStr = "";
for ($i=1;$i<500;$i++) {
    $valStr = $valStr . ($valStr == "" ? "" : ", ") . "('$i', '$i', '$i', NOW())";
}
if ($valStr != "") {
    mysql_query("Insert into accounts(id, username, email, password) VALUES $valStr");
}

```

Also, you should stop using `mysql_*` functions. They're being deprecated. Instead use [PDO](http://php.net/manual/en/book.pdo.php) (supported as of PHP 5.1) or [mysqli](http://php.net/manual/en/book.mysqli.php) (supported as of PHP 4.1). If you're not sure which one to use, [read this article](http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/).