• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Easy SQL query

#1
[eluser]ATomkins[/eluser]
Hi, Im trying to select the most recent record that has been entered into a table.
I think I can do this simplest by Getting a single record which has the largest value in the ID field, but Im not sure how to go about selection the highest.

Any help would be greatly appreciated. The table I will be retrieving out of is called "Personal"

Thank You for your time

Adam

#2
[eluser]Dam1an[/eluser]
If you want to get the id of the last inserted row, you can do
Code:
$this->db->insert_id();

Although if you insert into other tables between the last insert into the personal table and callling the last ID, you will get the ID of that table

The alternative is to just put a limit clause on a select to get a single row

#3
[eluser]ATomkins[/eluser]
I cannot get the $this->db->insert_id(); to work.
How can I limit it only to the last row otherwise?

I am attempting to use this:

$this->db->from('Personal');
$this->db->order_by("ID", "DESC");

$query = $this->db->get();
$data["personal"] = $query

Just to pass a reverse sorted query, but it crashed the site (just gives a white screen).
I know it should be annoyingly simple, but its just not clicking!

thanks for your time!

#4
[eluser]davidbehler[/eluser]
Code:
SELECT * FROM table ORDER BY id DESC LIMIT 0,1;
or
Code:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);

These 2 querys will get you the same result, the row with the highest id.

#5
[eluser]JoostV[/eluser]
You probably tried this already, but $this->db->insert_id() merely returns the id, so
a. you need to have inserted a record first, or $this->db->insert_id() will not return anything
b. you need to capture the insert id in order to be able to do anything with it.

Code:
// Insert a record
$this->db->insert('mytable', $data);

// Retrieve last inserted id
$id = $this->db->insert_id();

// Print the last inserted id to screen
var_dump($id);


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.