dongsou4301 2014-08-22 13:05
浏览 60

PDO基于lastInsertId()将新记录插入数据库

Ive just started learning PDO and I'm struggling by simply inserting a new record based from
$lastid = $db->lastInsertId();

The ID gets created in the database table from another function.

But nothing happens when i try to insert a new record based on that ID.

function add_name($last_id, $name) {
    $db = some_db();
    $query = "INSERT INTO team (name) VALUES (:name) WHERE id = '".$last_id."'";
    $stmt = $db->prepare($query);
    $stmt ->bindParam(':name', $name, PDO::PARAM_STR);
    $stmt->execute();
}
  • 写回答

2条回答 默认 最新

  • dsxcv5652 2014-08-22 13:08
    关注

    INSERT ... WHERE is not valid SQL. If you are inserting a new record, an autoincremnt ID will be generated at that time (if you have such defined for the table).

    If you are trying to INSERT a new row into a related table with the last id from another table, then you would set that value as one of your column inputs. So the workflow would look like this:

    INSERT [column data for table_a] INTO table_a
    [GET autoincrement from last insert]
    INSERT (table_a_foreign_key_column, [other table_b columns]) VALUES (table_a_id, [other table_b values) INTO table_b
    

    UPDATE:

    Since UPDATE is what you want, you can make update like this:

    UPDATE team
    SET name = :name
    WHERE id = :id
    

    You should use parameters for both name and id values. It is still not clear to me why you would need to make an insert and then an update within the same script execution. It's not like you received any more input from the user that you did not already have. I would guess you could just insert this name values when first creating the record and save yourself the extra trouble of multiple queries.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP