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 = ?
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;
}
Look at here Last Insert Id Already function available in PHP.
In your problem Use
$query->execute();
$last_inserted_id = $query->insert_id;
You can use
$id = mysql_insert_id();
Use this :
$db->lastInsertId();
For more info. see DOC
lastInsertId
is a method of PDO
, not PDOStatement