Why does the id always start from 1 when using pdo->exec to insert primary key column data in a PHP loop?
高洛峰
高洛峰 2017-06-26 10:49:02
0
1
585

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
Peter_Zhu

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!