kiriappa
kiriappa

Reputation: 832

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.

Upvotes: 2

Views: 54030

Answers (6)

Raham
Raham

Reputation: 4951

Try this,hope it helps,

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

Upvotes: 1

Abdullah Ayoub
Abdullah Ayoub

Reputation: 39

<?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

Upvotes: 0

Hamdan Shafiq
Hamdan Shafiq

Reputation: 11

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

Upvotes: 0

Ray Paseur
Ray Paseur

Reputation: 2194

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

Upvotes: 1

Shomz
Shomz

Reputation: 37701

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; 
}

Upvotes: 10

Derek Nutile
Derek Nutile

Reputation: 211

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

Upvotes: 5

Related Questions