[英]How to get max(id) of row data MySql
I want to get the maximum id of row data. 我想获得行数据的最大ID。 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.
在我的表中,第一列是id然后是firstname等。这是我用来获取行数据的max(id)的sql命令。
<?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.
但是在数据插入和更新之前,我只需要行数据的maximam id进行验证。
How to get the maxid. 如何获得maxid。 I use codeigniter framework.
我使用codeigniter框架。
Try this: 尝试这个:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE 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. 使用像“SELECT MAX(id)...”这样的原始查询的问题是它不是抽象的,可能不适用于每个SQL引擎。 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 请参阅: 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. 这将获得最高的id值,当我读到它时,“它打印出一堆数据,因为它是一个数组”我感觉到你真正想要的是该数组的一部分。 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 HTH,〜雷
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 错误未定义索引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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.