search

Home  >  Q&A  >  body text

Why does the id always start from 1 when using pdo->exec to insert primary key column data in a PHP loop?

Why does the id column inserted into the database always start from 1 through a loop?

<?php

$pdo = new PDO('mysql://host=localhost;dbname=test', 'root', 'root');
$pdo->exec('use test');
$pdo->exec('set names utf8');

$str = str_repeat('hi', 500);
$arr = range(1, 20);//生成1-20的数字,作为id列的值
shuffle($arr);//打乱id值在数组中的顺序

$statem= $pdo->prepare("insert into t2(id,c2,c3) values(?,?,?)");
foreach ($arr as $value)
{
        //不明白这里为什么插入到数据库中的id列的值始终从1开始,而打印出来的$value并不是从1开始的,而是乱序的
        $statem->execute(array($value,$str,$str));
}

//下面代码插入id值到数据库时数据库的id列是无序的,我要的就是这里的效果,但想通过12~16行的循环方式实现
$a = 22;
$b = 25;
$c = 44;
$r = $pdo->exec("insert into t2(id,c2,c3) values ($a,'$str','$str')");
$r = $pdo->exec("insert into t2(id,c2,c3) values ($b,'$str','$str')");
$r = $pdo->exec("insert into t2(id,c2,c3) values ($c,'$str','$str')");

The following is the structure of the t2 table

高洛峰高洛峰2739 days ago629

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-06-26 10:51:02

    What you inserted is unordered, it is just displayed in ascending order by id by default

    reply
    0
  • Cancelreply