Error to grab last ID

Asked

Viewed 102 times

0

Hi. I’m having trouble getting the last registered ID. I’ve made a lot of attempts, but the $proximo_ID variable always returns me '0', or Empty. You could help me solve the problem?

if(isset($_REQUEST['btn-cadastro'])) {

try {

    $wID = $_REQUEST['cadastro_ID'];

    $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);

    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $DB_con->prepare('SELECT ID FROM tbl_casualidade WHERE ID = :wID');
    $stmt->execute(array('wID' => $wID));
    $result = $stmt->fetchAll();

if (count($result)){ 

foreach($result as $row){

    $proximo_ID = $DB_con->lastInsertId();

        }
    }
}

catch(PDOException $e) {

    echo 'ERROR: ' . $e->getMessage();
    }

    $modelo = '<div id="link_'.$proximo_ID.'"></div>';

try {

    $sql = "INSERT INTO tbl_casualidade (ID, nome, modelo) VALUES ('$ID', '".$nome."', '".$modelo."')";

    $stmt = $DB_con->prepare($sql);

    $stmt->execute();
    echo "<div class='alert alert-success alert-dismissable' style='margin-top: 57px; margin-left: 45px; margin-bottom: -60px; margin-right: 15px;'>
            <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
            <strong>PERFEITO!</strong> Página cadastrada com sucesso...
        </div>";
    }

catch(PDOException $e)

    {
    echo "<div class='alert alert-danger alert-dismissable' style='margin-top: 57px; margin-left: 45px; margin-bottom: -60px; margin-right: 15px;'>
                <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
                <strong>FALHA!</strong> Por favor, tente enviar novamente...
            </div><br />";

    echo $sql . "<br>" . $e->getMessage();
    }

$DB_con = null;

}

  • Are you trying to get the last id before inserting? There is no need for 2 Try {} where you are only doing one operation in the bd.

  • Yes, that’s right. I need before inserting see which was the last ID and pass it to the variable $proximoID

  • So just use select max(id) + 1 as id from tbl_casualidade If you have not entered, there is no way to get the last inserted id.

  • But there is no way before I enter, I check what is the last id that is registered in the bank and add +1?

  • I’ve posted: select max(id) + 1 as id from tbl_casualidade $proximo_ID = $result[0]['id']

  • I did exactly as you said, but the value comes empty.

  • If it is the first record returns empty anyway! Fixing: select ifnull(max(id),0) + 1 as id from tbl_casualidade

  • Now it’s not empty, but there’s always 1.

  • Field id is not auto_increment | Identity ? Another question: where does $ID come from $sql = "INSERT INTO tbl_casualidade (ID, nome, modelo) VALUES ('$ID', '".$nome."', '".$modelo."')"; If auto_increment replace with $sql = "INSERT INTO tbl_casualidade (nome, modelo) VALUES ({$nome}, {$modelo})";

  • 2

    It worked. I was passing the $_REQUEST parameter with the wrong name. Thank you very much Maurivan.

  • Aiello, for nothing! Arrange.

  • If you want to add one more, do it $variavel++ with the result received

Show 7 more comments

1 answer

0


Has so:

$stmt = $DB_con->prepare('SELECT IFNULL (max(`ID`),0) FROM tbl_casualidade');
$stmt->execute();
$result = $stmt->fetchAll();
$ct=$result[0];

Or that:

$control=mysqli_query($conn,"select ifnull(max(ID),0)from tbl_casualidade");
$controll=mysqli_fetch_row($control);

$ct=$controll[0];

Particularly use the latter. This SELECT command selects and analyzes all records, returning the largest found at position [0].

  • Hello Danilo. Thank you so much for your help.

  • If helped accept the answer and point. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.