Jump to content

Formatting echo from database


Genesis730

Recommended Posts

So I have a database that stores First and last names, then echos them back to a website, as of now the entire first and last name echos back (John Smith)  I want the last name to just display the last letter and a . (John S.) here's my code for echoing the database

 

<?PHP
   $res = mysql_query("SELECT id, DATE_FORMAT(date, '%M %D %Y') as dt, firstname, lastname, testimonial FROM testimonials ORDER BY date DESC LIMIT 10");

   while ($row = mysql_fetch_assoc($res)) {
      echo "<p align=\"right\"><i>{$row['firstname']} {$row['lastname']}<br />{$row['dt']}</i></p><br /><br />{$row['testimonial']}<br /><hr width=\"80%\" color=\"#000000\"><br />";
   }
?>

Link to comment
Share on other sites

So I have a database that stores First and last names, then echos them back to a website, as of now the entire first and last name echos back (John Smith)  I want the last name to just display the last letter and a . (John S.) here's my code for echoing the database

 

<?PHP
   $res = mysql_query("SELECT id, DATE_FORMAT(date, '%M %D %Y') as dt, firstname, lastname, testimonial FROM testimonials ORDER BY date DESC LIMIT 10");

   while ($row = mysql_fetch_assoc($res)) {
      echo "<p align=\"right\"><i>{$row['firstname']} {$row['lastname']}<br />{$row['dt']}</i></p><br /><br />{$row['testimonial']}<br /><hr width=\"80%\" color=\"#000000\"><br />";
   }
?>

 

The most un-taxing and efficient method would be to use substr.

echo $row['firstname'] . substr($row['lastname'], 0 , 1) . ".";  //John S.

Link to comment
Share on other sites

Better still, format your data within your query.

 

SELECT id, DATE_FORMAT(date, '%M %D %Y') as dt, firstname, CONCAT(SUBSTR(lastname, 0, 1),'.') AS formatted_lastname, testimonial FROM testimonials ORDER BY date DESC LIMIT 10

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.