doufangzhang4454 2016-02-17 16:03
浏览 247
已采纳

从上次插入到表中获取ID

Im inserting into multiple tables , and need to get the ID from the last insert into table1 and use that as a variable in the insert for table 2.

The IDs is auto incremented.

The query's will be run once a submit button has been clicked in a form.

Query's:

$sql = "INSERT INTO table1 (Text) VALUES ($T1text);";
$sql = "INSERT INTO table2 (table1ID,Text) VALUES ($table1id, $T2text);";


table1 {id,Text}
table2 {id,table1.id,Text}
  • 写回答

1条回答 默认 最新

  • duanrou5680 2016-02-17 16:41
    关注

    There is a PHP function for that (Decprecated, Removed in 7.0 !) Or the according mysql/mysqli/pdo functions.

    Solutions

    PHP (Deprecated)

    Example

    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
     die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('mydb');
    
    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    printf("Last inserted record has id %d
    ", mysql_insert_id());
    

    Source: http://php.net/manual/en/function.mysql-insert-id.php

    Mysql/Mysqli/PDO

    Mysqli $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

    if (mysqli_query($conn, $sql)) {
        $last_id = mysqli_insert_id($conn);
        echo "New record created successfully. Last inserted ID is: " . $last_id;
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
    

    PDO

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";
    // use exec() because no results are returned
    $conn->exec($sql);
    $last_id = $conn->lastInsertId();
    

    Source: http://www.w3schools.com/php/php_mysql_insert_lastid.asp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥30 数字信号处理实验报告
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要