如何在插入后获取数据

时间:2015-12-23 16:47:42

标签: php mysql

我在mysql表中插入一行,然后我尝试获取插入的数据自动递增的id。但不幸的是它不起作用......

我的代码看起来像 -

$q4 = $query - > prepare('INSERT INTO tblstate(state, country_id) VALUES(:state, :country_id)', $con);
$res4 = $query - > InsertState($q4, $state, $country_id);

if (isset($res4)) {
    $q5 = $query - > prepare('SELECT * FROM tblstate WHERE state=:state', $con);
    $res5 = $query - > SelectState($q5, $state);
    $state_id = $res5['state_id'];

}

表结构是 -

Table name: tblstate Fields: state_id(AUTO_INCREMENTED)(PK), state, country_id

function InsertState($q, $state, $country_id) {
    $q - > execute(array('state' => $state, 'country_id' => $country_id));
    return self::Result($q);
}

function SelectState($q, $state) {
    $q - > execute(array('state' => $state));
    return self::Result($q);
}

1 个答案:

答案 0 :(得分:1)

猜猜你正在使用PDO。尝试:

$query->lastInsertId();

有关详细信息,请参阅documentation for PDO::lastInsertId