PHP致命错误:调用未定义的函数LAST_INSERT_ID()

时间:2016-03-16 06:18:48

标签: php mysql pdo

我在数据库的两个表中插入数据。我使用了LAST_INSERT_ID()函数

但我收到此错误

  

PHP致命错误:调用未定义的函数LAST_INSERT_ID()

这是我的代码:

$sql = "";
$sql .= "BEGIN; ";
$sql .= "INSERT INTO circle_call_prefixes (";
$sql .= "  circle";
$sql .= " ,prefix";
$sql .= " ) VALUES (";
$sql .= "  :cid";
$sql .= " ,:prefix";
$sql  = "INSERT INTO circle_call_destinations (";
$sql .= "  autoNo";
$sql .= " ,destination";
$sql .= " ,source_circle";
$sql .= " ) VALUES (";
$sql .= LAST_INSERT_ID();
$sql .= " ,:prefix";
$sql .= " ,:prefix";
$sql .= " COMMIT; ";
$sql .= " );";
$stmt = $dbh->prepare($sql);
foreach($Insert_array as $e1)
{
    $stmt->bindValue(':circle', $e1['cid']);
    $stmt->bindValue(':prefix', $e1['prefix']);
    $stmt->bindValue(':comment', $e1['comment']);
    $stmt->bindValue(':cid', $Cid);
    $stmt->execute();
}

感谢

2 个答案:

答案 0 :(得分:2)

LAST_INSERT_ID在SQL中,试试这个:

$sql = "";
$sql .= "BEGIN; ";
$sql .= "INSERT INTO circle_call_prefixes (";
$sql .= "  circle";
$sql .= " ,prefix";
$sql .= " ) VALUES (";
$sql .= "  :cid";
$sql .= " ,:prefix";
$sql  = "INSERT INTO circle_call_destinations (";
$sql .= "  autoNo";
$sql .= " ,destination";
$sql .= " ,source_circle";
$sql .= " ) VALUES (";
$sql .= "LAST_INSERT_ID()";
$sql .= " ,:prefix";
$sql .= " ,:prefix";
$sql .= " COMMIT; ";
$sql .= " );";
$stmt = $dbh->prepare($sql);

foreach($Insert_array as $e1){
              $stmt->bindValue(':circle', $e1['cid']);
              $stmt->bindValue(':prefix', $e1['prefix']);
              $stmt->bindValue(':comment', $e1['comment']);
              $stmt->bindValue(':cid', $Cid);
              $stmt->execute();
             }

答案 1 :(得分:0)

因为LAST_INSERT_ID()是Mysql的一个函数,你已经把它作为PHP函数,有时使用字符串append会导致这类问题,最好使用字符串块如下所示。

$sql = <<<SQL
        BEGIN;
        INSERT INTO circle_call_prefixes(circle ,prefix)
        VALUES (:cid, :prefix);
        INSERT INTO circle_call_destinations(autoNo, destination, source_circle)
        VALUES (LAST_INSERT_ID(), :prefix, :prefix);
        COMMIT;
SQL;