Вопрос

I know this is a basic question but i can't work out how i can amend my query to just display the last record inserted to that table. If i was using mysqli_query i would have something like(not perfect as just a quick example):

$stmt = DB::query(Database::SELECT, 'SELECT `fname`,`lname`,`postcode`,`email` FROM `mytable` ORDER BY `id` DESC LIMIT 1;)
                VALUES (:fname, :lname, :postcode, :email)');   
$stmt->execute();
$result=mysqli_query($stmt);
echo "<table border='1'><tr><th>First Name</th></tr>";
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>" . $row['fname'] . "</td>";
echo "</tr>";

In Kohana I currently have the following which is working fine except it is displaying all users and I just want the last record/user inserted to be displayed, how can I implement the query from the first(mysqli) bit of code to the second(Kohana)

$results = DB::select('fname', 'lname', 'postcode', 'email')->from('mytable')->execute();
$users = $results->as_array();
foreach($users as $user)
{
echo 'First Name: '.$user['fname'];
echo 'Last Name: '.$user['lname'];
echo 'Postcode: '.$user['postcode'];
echo 'Email: '.$user['email'];
}
Это было полезно?

Решение

You are missing the ORDER BY and LIMIT, why not implement them using the query builder's methods order_by() and limit()?

$results = DB::select('fname', 'lname', 'postcode', 'email')->from('mytable')
  ->order_by('id', 'DESC')->limit(1)->execute();

Другие советы

Or if using ORM

ORM::factory('table')->order_by('id', 'DESC')->limit(1)->find();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top