php mysqli last record

Asked

Viewed 331 times

0

I have a page that makes connection through the mode mysqli class below:

# include da classe

class connectionClass extends mysqli{
    public $host="localhost",$dbname="banco",$dbpass="",$dbuser="susus";
    public $con;

    public function __construct() {
        if($this->connect($this->host, $this->dbuser, $this->dbpass, $this->dbname)){}
        else
    {
        return "<h1>Erro de conexão/h1>";
    }
}
}

page where it is called the class

require_once 'connectionClass.php';

class webcamClass extends connectionClass{

    $query  =   "INSERT INTO vis_pres_path_foto (fk_id_user_sistema,vis_pres_path_foto_image) ";
    $query  .=  "VALUES('$id_user','$image') ";
    $result =   $this->query($query);
}

Like I do after the insert above return the last id of the table after the insert in the PDO I use $ultimo = $conn->lastInsertId(); but, for this case does not work.

  • first notice that your if and Else are within the same key, fix it in your code because the correct syntax is if { parametres } Else { parametres } and not in the way you indicate if{ parametres ... Else {} {

  • $this->insert_id

2 answers

1

after correcting the syntax of your code you can create a function like this

<?php
/*
 * Description of LastId
 *
 * @author Adriano Back
 */
class LastId {

private $id;

    public function __construct(){
        $conn = mysqli_connect(DBURI,DBUSER,DBPASS,DBNAME);
        if (mysqli_connect_error())
        {
            exit("Falha de Conexão: <br />" . mysqli_connect_error());
        }

        $query = "SELECT id FROM suatabela ORDER BY id DESC LIMIT 1";
        $result = mysqli_query($conn,$query) or 
                die(mysqli_error($conn) . " Falha de Consulta " . $query);


        $id = mysqli_fetch_assoc($result);

        foreach($id as $last_id){
            $this->id = $last_id['id'];
        }    
        mysqli_close($conn);
    }

    public function getLastId(){
        return $this->id;
    }
}

then you charge so

$id = new LastId();
$last_id = $id->getLastId();
  • Ai was in the POG in kk

  • hehe to accustomed with Pdo not even remember how he did in mysqli

  • but I don’t even know what POG means

1


The class mysqli owns the int $insert_id, which returns the last id generated by mysql, see how to use in your situation:

    $query  =   "INSERT INTO vis_pres_path_foto (fk_id_user_sistema,vis_pres_path_foto_image) ";
    $query  .=  "VALUES('$id_user','$image') ";
    $result =   $this->query($query);
    $ultimoId = $this->insert_id;
  • That’s right, now it worked, that’s what I needed. It returns the last id inserted in the table.

Browser other questions tagged

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