PHP问题插入auto_increment

时间:2018-05-09 08:52:51

标签: php pdo

我是PHP代码的新手。 我有一个我要插入的表格,但由于某种原因,插入语句不起作用。表格有一个AUTOIDINCREMENT的ScanID列。我尝试过一些事情,比如将ScanID从语句中删除,但这也没有用(我也试过用''交换NULL)。我能够插入到没有AUTO_INCREMENT的ID的其他表中,所以我非常确定我的连接有效。

<?php

$xml=simplexml_load_file("someFile.xml");
$con =new PDO("mysql:host=localhost;dbname=testDB",'root','');



$ScanType="someType";
$start_date=$xml ->start_datetime;
$end_date=$xml ->finish_datetime;

$TargetTargetID="1";
$stmt=$con->prepare('insert into
Scan(ScanID, ScanType, start_date, end_date, TargetTargetID) values
(:ScanID, :ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanID',NULL);
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();

$ScanID=$con->lastInsertId();
echo $ScanID;
?> 

编辑:这对我有用

$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');

$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();

1 个答案:

答案 0 :(得分:1)

无需在插入查询中传递自动增量列值,只需从列和值中删除

即可
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');

从绑定值中删除

$stmt->bindValue('ScanID',NULL);