简体   繁体   中英

How to get max(id) of row data MySql

I want to get the maximum id of row data. In my table first column is id then firstname and etc. this is the sql command I used to get the max(id) of row data.

<?PHP  $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
                print_r( $maxid) ;?>

but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.

How to get the maxid. I use codeigniter framework.

Try this:

$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;

UPDATE

This will work even if your table is empty (unlike my example above):

$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
    $maxid = $row->maxid; 
}

The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:

$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details

See: http://ellislab.com/codeigniter/user-guide/database/active_record.html

SELECT id FROM table ORDER BY id DESC LIMIT 1

That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:

$maxid = (int)$maxid['id'];

or like this (if you have an object):

$maxid = (int)$maxid->id;

HTH, ~Ray

public function getMaxCategoryId() {
    $query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
    return $query->row['maxid'];
}

error undefined index maxid

<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>

After Connection Just Write This Code It Will Work

Try this,hope it helps,

return $this->db->select_max('id')
                        ->get('your_table_name')
                        ->row()->id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM