Jump to content

select last row


matttherat

Recommended Posts

hi. just started a website talkietaco.com and at the momment my code selects the first row and displays it. this is all well and good but when i add a new row to the table it gos to the bottom. I want to be able to select the last row and echo it out. Any ideas? would i need to add an id row or something?

Heres the code and thank you in advance for any help people can offer.

 

<?php


$con = mysql_connect("localhost","","");



if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  
mysql_select_db("mainbase", $con);


$result = mysql_query("SELECT * FROM matteroffact");

echo "<table border='0'>
<tr>
<th></th>
</tr>";

$row = mysql_fetch_array($result) or die(mysql_error());
echo "<tr>";
echo "<td><strong>" . $row['question']. "</strong>  ". $row['answer']; "</td>";
echo "<tr>";

echo "</table>";


?>

Link to comment
https://forums.phpfreaks.com/topic/212372-select-last-row/
Share on other sites

Dedicated concatenation is sooooo yesterday, use braces instead itll clean up your code and it can handle arrays

 

<?php

$con = mysql_connect("localhost","","");

if (!$con){
  die('Could not connect: ' . mysql_error());
  }
  
mysql_select_db("mainbase", $con);

$result = mysql_query("SELECT * FROM matteroffact");

echo "<table border='0'>
<tr>
<th></th>
</tr>";

$row = mysql_fetch_array($result) or die(mysql_error());
echo "<tr><td>
          <strong>{$row['question']}</strong> {$row['answer']}
          </td><tr>
          </table>";

?>

Link to comment
https://forums.phpfreaks.com/topic/212372-select-last-row/#findComment-1106645
Share on other sites

also if you're looking for the last inserted id I would use this

select last_insert_id() as lastid from table limit 1 

 

that actually gets the id of the last row inserted by the current connection. This saves you headaches further down the road if you get more than one connection putting data into your database.

Link to comment
https://forums.phpfreaks.com/topic/212372-select-last-row/#findComment-1106650
Share on other sites

also if you're looking for the last inserted id I would use this

select last_insert_id() as lastid from table limit 1 

 

that actually gets the id of the last row inserted by the current connection. This saves you headaches further down the road if you get more than one connection putting data into your database.

 

Even better:

 

mysql_query("bla bla");
$id = mysql_insert_id();

Link to comment
https://forums.phpfreaks.com/topic/212372-select-last-row/#findComment-1106653
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.