1

I am trying to return the last id and increment it to put in the value attribute. I can make it work with old mysql but not with the PDO. I am learning (I think) PDO but it is not making sense.

Below is the code.

    <td><label for="invNum"></label>Invoice</td>
    <?php
    $stmt = $dbconn->prepare("SELECT max(invId) FROM     invoices");
    $stmt->execute();
    $invNum = $stmt->fetch();
    
    /* mysql_select_db("customers", $dbconn);
    $result = mysql_query("SELECT max(invId) FROM   invoices");
    if (!$result) {
    die('Could not query:' . mysql_error());
    }
    $invNum = mysql_result($result, 0);*/
    ?>
    <td><input type="text" name="invNum" id="invNum" 
    size="12" value="<?php echo ++$invNum; ?>" /></td>
  • 1
    Why don't you use `::lastInsertId()`? http://php.net/manual/en/pdo.lastinsertid.php – D4V1D Mar 29 '15 at 18:14
  • Simply assuming that you can take the last ID and add one to it only works if nobody else ever uses your system.... the moment you have a second user is the moment it breaks – Mark Baker Mar 29 '15 at 18:15
  • 3
    You should have an auto-incremented column and then use `lastInsertId()` if you need the value. – Gordon Linoff Mar 29 '15 at 18:18
  • I'm just trying to build a Invoice template for personal use and education. So nobody else will be using it. I don't understand the php manual instructions. Thank you Pat –  Mar 29 '15 at 18:33
  • So the question is really about prepare+execute+fetch. What do you get in `$invNum`? Do you have any error messages? – Rick James Mar 30 '15 at 20:17

2 Answers2

5

Try this :

  $stmt = $dbconn->prepare("SELECT MAX(invId) AS max_id FROM invoices");
  $stmt -> execute();
  $invNum = $stmt -> fetch(PDO::FETCH_ASSOC);
  $max_id = $invNum['max_id'];
Ioannis P.
  • 131
  • 1
  • 6
1

If you want to enter a new line right away:

$pdo = new PDO('mysql:host=localhost;dbname=databasename','username','password');

$statement = $pdo->prepare("INSERT INTO invoices(data1, data2, data3) VALUES (?, ?, ?)");
$statement->execute(array('bla', 'bla', 'bla'));   

$newID = $pdo->lastInsertId();
Shenya
  • 334
  • 1
  • 3
  • 14