Error to get last ID

0

Hello. I'm having trouble getting the last logged in ID. I have already made a lot of attempts, but the variable $ proximo_ID always returns me '0', or Empty. Could you 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;

}

    
asked by anonymous 11.02.2017 / 21:05

1 answer

0

It looks like this:

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

Or this:

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

$ct=$controll[0];

I particularly use this last one. This SELECT command selects and parses all records, returning the highest found in position [0].

    
12.02.2017 / 20:33