Jump to content

Shorten and dispaly text from database row


ow-design

Recommended Posts

Hi everybody i am a little stuck at the moment, I am creating a site that needs to display on the home page a shortened title of a news story that a user can click to get full story.

I have the shortening code:

<?php
function ShortenText($text) {

        // Change to the number of characters you want to display
        $chars = 80;

        $text = $text."database row would go here";
        $text = substr($text,0,$chars);
        $text = substr($text,0,strrpos($text,' '));
        $text = $text."...";

        return $text;

    }

?><p></p>

<?php
echo ShortenText($text);
?>

 

But i need this code to bring up the newest 3 rows of a database table that holds the news stories and display the shortened content.

 

Any ideas?

Thank You

To get the latestest 3 rows from the database you'll apply LIMIT 3 to your query, eg

 

function ShortenText($text, $chars=80)
{
        $text = substr($text,0,$chars);
        $text = substr($text,0,strrpos($text,' '));
        $text .= '...';

        return $text;
}

// get the latest 3 news feeds
$sql = 'SELECT news_title_field from news_table ORDER by news_id_field DESC LIMIT 3';
$result = mysql_query($sql);

// display news
while($row = mysql_num_assoc($result))
{
     // display shortened news title, returns the first 30 chars.
     echo shortText($row['news_title_field'], 30);
}

 

NOTE: I made $chars an optional parameter for your function.

<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  ?>
<?php
function ShortenText($text, $chars=80)
{
        $text = substr($text,0,$chars);
        $text = substr($text,0,strrpos($text,' '));
        $text .= '...';

        return $text;
}

// get the latest 3 news feeds
$sql = 'SELECT title from table ORDER by id LIMIT 3';
$result = mysql_query($sql);

// display news
while($row = mysql_num_rows($result))
{
     // display shortened title, returns the first 30 chars.
     echo shortText($row['title'], 80);
    }
     ?>

 

however the following is displayed now

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/deswo/public_html/clients/baseyouthproject/shorten_a_text_string1.php on line 27

 

line 27 is

while($row = mysql_num_rows($result))

 

please help :)

Thank You

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.