0

I'm trying to get latest inserted id from a table using this code:

$id = $tbl->fetchAll (array('public=1'), 'id desc');

but it's always returning "1"

any ideas?


update: I've just discovered toArray();, which retrieves all the data from fetchAll. The problem is, I only need the ID. My current code looks like this:

$rowsetArray = $id->toArray();
$rowCount = 1;

foreach ($rowsetArray as $rowArray) {
    foreach ($rowArray as $column => $value) {
       if ($column="id") {$myid[$brr] = $value;}
      //echo"\n$myid[$brr]";
    }
    ++$rowCount;
    ++$brr;
}

Obviously, I've got the if ($column="id") {$myid[$brr] = $value;} thing wrong. Can anyone point me in the right direction?

An aternative would be to filter ID's from fetchAll. Is that possible?

  • maybe a duplicate of http://stackoverflow.com/questions/1868769/zend-framework-how-to-retrieve-the-id-of-the-last-inserted-row ? – Samuel Herzog Jan 07 '11 at 10:44
  • it's not the same, because I'm not using it after inserting new row –  Jan 13 '11 at 10:01
  • to clarify this further, I need to get ID's of articles that are published (hence 'public=1'), so I can write links to most recent articles. –  Jan 13 '11 at 10:07

4 Answers4

1

Think you can use:

$id = $tbl->lastInsertId();
opHASnoNAME
  • 20,224
  • 26
  • 98
  • 143
  • It returns undefined function error, probably because I'm not using it after insert. –  Jan 13 '11 at 10:05
1

Aren't you trying to get last INSERT id from SELECT query?

Use lastInsertId() or the value returned by insert: $id = $db->insert();

greg606
  • 491
  • 3
  • 17
1

Why are you using fetchAll() to retrieve the last inserted ID? fetchAll() will return a rowset of results (multiple records) as an object (not an array, but can be converted into an array using the toArray() method). However, if you are trying to reuse a rowset you already have, and you know the last record is the first record in the rowset, you can do this:

$select = $table->select()
    ->where('public = 1')
    ->order('id DESC');
$rows = $table->fetchAll($select);
$firstRow = $rows->current();
$lastId = $firstRow->id;

If you were to use fetchRow(), it would return a single row, so you wouldn't have to call current() on the result:

$select = $table->select()
    ->where('public = 1')
    ->order('id DESC');
$row = $table->fetchRow($select);
$lastId = $row->id;
Andrew
  • 227,796
  • 193
  • 515
  • 708
0

It sounds like it's returning true rather than the actual value. Check the return value for the function fetchAll

Matt Asbury
  • 5,644
  • 2
  • 21
  • 29
  • according to http://php.net/manual/en/pdostatement.fetchall.php, fetchAll should return an array.. maybe I'm getting something wrong –  Jan 13 '11 at 10:04