Jump to content

Fetch last records added from multiple tables; Mysql & PHP.


musnoure

Recommended Posts

...I have multiple categories; auto, family, business &finance... and I set up one table for each category in Mysql. I'd like to retrieve the last two records added. ("SELECT * from table_name ORDER BY id DESC LIMIT 3");

This works but only for one table. What if I added new articles in different tables, let's say I added one article in *family*one in *auto* and another in *pets*.

 

Any help is appreciated, thank you!

Link to comment
Share on other sites

Salam :)

 

I am going to comment on this post

 

What I really want to achieve is getting the last row inserted from each table.

 

It is squandering to create a new table for each category, however if the circumstances calls for it, I don't object. I don't know if there is a special statement in Mysql for this, but I do know if you are inserting something in your table, you can call mysql_insert_id() on the same page to get the id of the data you just inserted into your table.

 

edit: I thought you wanted to grab the last 2 rows. sorry, however read this post, i suggested a function.

Link to comment
Share on other sites

Hy,

Here's an example that gets the las inserted id (I use MySQLi):

<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

// sql query for INSERT INTO users
$sql = "INSERT INTO `users` (`name`, `pass`, `email`)
VALUES ('PloMar ', 'love_light', 'a_name@domain.net')"; 

// Performs the $sql query and get the last insert auto ID
if ($conn->query($sql) === TRUE) {
  echo 'The auto ID is: '. $conn->insert_id;
}
else {
echo 'Error: '. $conn->error;
}

$conn->close();
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.