doutany76678 2013-12-19 06:48 采纳率: 0%
浏览 44
已采纳

如何从插入的数据中获取id

Hi guys im having difficulty on creating a logic on how to get an ID to an inserted data.My page has no userID or any. Just insertion of the data. I have two tables:

request to purchase table and ordered_items table. I separated the tables because i just need to store multiple data for items which hold an array of data.

heres my code:

<td><textarea name="item[]" value=""></textarea></td>
<td><textarea name="description[]" value=""></textarea></td>
<td><input type="text" name="qty[]" value="" /></td>
<td><input type="text" name="amount[]" value="" /></td>
<td><button class="add">Add</button></td>

and my methods are here:

public function insertRecord($param1, $param2, $param3, $param4) {

    $query = $this->db->prepare('INSERT INTO `request_to_purchase` (`requestedby`, `date`, `jobtitle`, `supervisor`, `notes`) VALUES (?, NOW(), ?, ?, ?)');

    $query->bindValue(1, $param1, PDO::PARAM_STR);
    $query->bindValue(2, $param2, PDO::PARAM_STR);
    $query->bindValue(3, $param3, PDO::PARAM_STR);
    $query->bindValue(4, $param4, PDO::PARAM_STR);

    try {

        $query->execute();

        $row = $query->rowCount();

        echo $row;

        if(count($row) > 0) {

            return true;
        } else {                
            return false;
        }

    } catch(PDOException $e) {

        die($e->getMessage());

    }

}

public function insertItem($arg1, $arg2, $arg3, $arg4, $arg5, $arg6) {

    $query = $this->db->prepare('INSERT INTO `ordered_item` (`rtp_id`, `item`, `description`, `qty`, `amount`, `date`) VALUES (?, ?, ?, ?, ?, ?)');

    $query->bindValue(1, $arg1);
    $query->bindValue(2, $arg2);
    $query->bindValue(3, $arg3);
    $query->bindValue(4, $arg4);
    $query->bindValue(5, $arg5);
    $query->bindValue(6, $arg6);
}

How do i get the rtp_id from request_to_purchase table so that i can insert it on the ordered item table. By then I can make a query Select * from ordered item table where rtp_id = ?

  • 写回答

4条回答 默认 最新

  • dongzanxun2790 2013-12-19 07:02
    关注

    In PDO you can do like this:

    $db->lastInsertId('yourIdColumn');
    

    Docs Link: http://pt2.php.net/manual/en/pdo.lastinsertid.php

    In your code snippet.

      if(count($row) > 0) {
    
            return $this->$db->lastInsertId();
        } else {                
            return false;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)