Jump to content

Using a variable in title tag


adamcroft

Recommended Posts

Hi all,

 

Looking for some help with a small problem I've got. I'm pretty new when it comes to PHP, so I'm a bit stuck.

 

On a website I run, there's a news script which allows me to easily add news to the website. However, I've noticed that each news item, despite having a different URL through variables, uses the same title tag (due to news.html containing an include to the easynews.php file which pulls news from the database).

 

The news page URL is http://www.thisisdunstable.co.uk/news.html

 

I'd like each news story to have a different title tag - perhaps '[headline here] - Latest news from This is Dunstable', and am getting a bit stuck. I think I need to call the easynews.php file before the title tag declaration, but doing so would break the page as easynews.php contains write and echo commands. I've tried editing the code to remove the write and echo commands and save that as a differently-named PHP file to call, but that didn't work either (probably due to my PHP noob-ness).

 

Does anyone have any ideas as to how I can easily take the $title variable from easynews.php and use it in the title tag of news.html? BTW - I've set .htaccess to parse .html files as PHP.

Link to comment
Share on other sites

If i am right in every page you include a file in every page that does all the working out, try something like this; it will work based on the page URL.

 

if($_SERVER['SCRIPT_NAME']  == '/news.php') {

    // ... get page titles
    $title = $newsTitle . ' - Latest news from This is Dunstable';

} else {

    $title = 'Dunstable, Bedfordshire - Information, and local resources from This is Dunstable';

}
echo '<title>'.$title.'</title>';

Link to comment
Share on other sites

Could you post the code of the new.html and easynews.php?

 

Sure. Here's news.html:

 

<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Dunstable, Bedfordshire - Information, and local resources from This is Dunstable</title>
<meta name="description" content="Dunstable, Bedfordshire - Information, and local resources from This is Dunstable" />
<meta name="keywords" content="dunstable, bedfordshire" />
<meta name="Robots" content="index,follow" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<div id="container">
<?php include("includes/header.shtml"); ?>
<div id="menu-left">
<?php include("includes/menu.shtml"); ?>
</div>
<div id="content">
<h3><span class="green">this</span><span class="grey">is</span><span class="blue">news</span></h3>
<?php include_once("news/easynews.php"); ?>
</div>
<div id="sidebar">
<?php include("includes/sidebar.shtml"); ?>
</div>
<div style="clear:both;"></div>
</div>
<div id="footer"><?php include("includes/footer.shtml"); ?></div>

</body>
</html>

 

And here's easynews.php:

 

<?php
/*******************************************************************************
* Easynews::easynews.php
* 
* Description: Shows news in database.
* Author: C4F Team (http://code4fun.org)
*  
*******************************************************************************/

/************************ SETTING UP SOME VARIABLES ***************************/

// include configuration variables
include 'config.php';

// build images path
$imgpath = $enPath.'images/';

// rectify $enPath
validatePath($enPath);

// build emoticons path
$emoPath=$enPath.'emoticons/';
   
// check if this file is called for preview
if ($easynewsPreview) { $imgpath='images/'; $emoPath='emoticons/'; }

// includes some useful functions...
include 'includes/functions.php';

/*********************** ESTABLISH DBMS CONNECTION ***************************/

// database connection
$conn = @mysql_connect($db_host, $db_user, $db_pw) or die ('Error during DBMS connection:<br />' . mysql_error() );
@mysql_select_db($db_name,$conn) or die ('Error during database selection:<br /> ' . mysql_error() );

/************ View full news item (link "read more")  **************/

if (isset($_GET['id'])) {

$id = (int)$_GET['id'];
$query = 'SELECT * FROM `'.$table_name.'` WHERE newstime='.$id.'';
// send query and get the resulting number of rows
$result = @mysql_query($query,$conn) or die ('Error reading news from database, check config.php file and run setup.php first:<br />' . mysql_error() );

if ($num_rows = @mysql_num_rows($result)) $flagId=true;
else $flagId=false;
}

/**************************** GET NEWS FROM DB ********************************/

// if $_GET['id'] is not set or $num_rows is null (id hack) then show news
if ( !isset($_GET['id']) || !$num_rows) {

// check page variable
if ( !isset($_GET['page']) || $_GET['page']<1 ) $page = 1;
else $page = $_GET['page'];

// get all news
$query = 'SELECT * FROM `'.$table_name.'`';
// send query and get affected rows number
$result = @mysql_query($query,$conn) or die ('Error reading news from database, check config.php file and run setup.php first:<br />' . mysql_error() );
$num_rows = @mysql_num_rows($result);

// calculate how many pages of news
$pages = intval($num_rows/$newscount);
if ($num_rows%$newscount) $pages++;

// check if a wrong page is manually typed
if ($page > $pages) $page = 1;

// get current page news
$recordStart=($page*$newscount)-$newscount;
$query = 'SELECT * FROM `'.$table_name.'` ORDER BY newstime DESC LIMIT '.$recordStart.','.$newscount;
$result = @mysql_query($query,$conn) or die ('Error reading news from database, check config.php file and run setup.php first:<br />' . mysql_error() );
}

/********************************* SHOW NEWS **********************************/

if ($num_rows) {

while (list($time, $text, $imageName, $align, $link, $title) = mysql_fetch_row($result)) {

	// define full-story link
	$fullStoryLink = '<a style="text-decoration: none;" href="'.$_SERVER['SCRIPT_NAME'].'?id='.$time.'&page='.$page.'">';

	// define date and title style
	$date='<span style="font-family: Verdana; color: '.$dateColor.'; font-weight: '.$dateBoldness.'; padding: 2px;"></span>';
                       
	// if title exist append the date
	if ($title!='') $date.='<span style="font-family: Verdana; font-size: 1.4em; color: '.$titleColor.'; font-weight: '.$titleBoldness.';">'.$title.'</span>';
	       
	// truncate the text on charMax
	if (!$flagId && $charMax>0) $text = stringCutter($text, $charMax, $fullStoryLink);
	// convert text emoticons to corresponding images
        $text = doReplace($text , $emoticons['char'], $emoticons['icon'] );

        
	// image handling
	if ($imageName!='') {

		// user submitted link
		if ($link!='') $image = '<a href="'.$link.'">';

		// image link to itself
		else $image = '<a href="'.$imgpath.$imageName.'">';
                  
        // image alignment
        if ($align=='left') $padding = '2px 5px 0px 0px';
        else $padding = '2px 0px 0px 5px';
        $image.='<img style="float: '.$align.'; padding: '.$padding.'; border: 0;" src="'.$imgpath.$imageName.'" alt="news image" '.imgSize($imgpath.$imageName , ($imgRatio/100)).' /></a>';
	}
	else $image=''; // reset the variable

	// print single news
	echo '<table style="width: '.$tableWidth.'px; border: 0; padding: 0; margin-bottom: '.$newsSpacer.'px;">
			 <tr><td style="border-width: '.$tableBorder.'px '.$tableBorder.'px 0 '.$tableBorder.'px; border-style: solid; border-color: '.$borderColor.'; text-align: '.$textAlign.'; padding: 0 2px 2px 2px; background-color: '.$dateBgColor.';">'.$date.'</td></tr>
			 <tr><td style="border-width: 0 '.$tableBorder.'px '.$tableBorder.'px '.$tableBorder.'px; border-style: solid; border-color: '.$borderColor.'; text-align: left; padding-left: 5px; padding-right: 5px; background-color: '.$textBgColor.'; font-family: Verdana; font-size: 1em; line-height: 150%; color: '.$textColor.'; font-weight: '.$textBoldness.';">'.$image.$text.'</td></tr>
<tr><td> </td></tr>';

	if ($flagId) {

		echo '<tr><td style="font-family: Verdana; font-size: '.$dateSize.'px; color: '.$dateColor.'; font-weight: '.$dateBoldness.'; padding: 2px; border-width: '.$tableBorder.'px; border-style: solid; border-color: '.$borderColor.'; background-color: '.$dateBgColor.';">
	 			<span style="float:left;"></span>
	 			<span style="float:right;"><a style="text-decoration: none;" href="'.$_SERVER['SCRIPT_NAME'].'?page='.$page.'">back to news</a></span>
		 	  </td></tr>';
	}
	print '</table>'."\n";

} // end while loop

if (!$flagId) {

	// print html table footer and paginator
    echo '<table style="width: '.$tableWidth.'px; border: 0; padding: 0; margin: 0;">
	 	  <tr><td style="border: '.$tableBorder.'px solid '.$borderColor.'; text-align: center; font-family: Verdana; font-size: '.$textSize.'px; color: '.$textColor.'; background-color: '.$textBgColor.'; padding: 4px;">';
  		if ($page>1) print '<a style="text-decoration: none;" href="'.$_SERVER['SCRIPT_NAME'].'?page='.($page-1).'"><</a> ';
    
    print ' Page ['.$page.'/'.$pages.']';

	if ($page<$pages) print ' <a style="text-decoration: none;" href="'.$_SERVER['SCRIPT_NAME'].'?page='.($page+1).'">></a>';

	print '</td></tr><tr><td style="font-size: 10px; font-family: Verdana; text-align: right;">powered by <a style="text-decoration: none;" href="http://code4fun.org">EasyNews</a></td></tr></table>';
}
} // end if ($num_row)

// warn user if no news in db ($num_row<1)
else print '<div style="padding: 4px; text-align: center; font-family: Verdana; font-size: 12px; color: #000000;">No News In Database</div>';

// close db connection
@mysql_close($conn);

/****************************** EXTRA FUNCTIONS *******************************/

/**
* Sets image size according to $maxWidth and $margin 
* 
* @param String img - image url  
* @param integer ratio - ratio in percentage (relative to table width)
*  
*/
function imgSize($img, $ratio) {

	 global $tableWidth,$contentPadding;
	 if ($ratio>100) $ratio=100;

	 $maxWidth = round(($tableWidth - 2*$contentPadding)*$ratio);
         // Get the size of news image
         if (!$size = @getimagesize($img)) {
		$newWidth = $maxWidth;
		return 'width="'.$newWidth.'"';
 	 }
	 $width=$size[0];
	 $height=$size[1];
         // get height/width ratio of the real image
         $imgRatio = $height/$width;
         // get new size from height/width ratio
         if ($width>$maxWidth) {
                 $newWidth = $maxWidth;
                 $newHeight= round($newWidth*$imgRatio);
         }
         else { $newWidth=$width; $newHeight=$height; }
         return 'width="'.$newWidth.'" height="'.$newHeight.'"';
}

/**
* Validate a path adding the "http" protocol if missing and the final slash if
* missing
* 
* @param String path - Url to validate
*/
function validatePath(&$path) {

if (substr($path,0,4)=='www.') $path='http://'.$path;
if ($path{0}=="/") $path=substr($path, 1);
if ($path{strlen($path)-1}!="/" && $path!="") $path.="/";
}
?>

Link to comment
Share on other sites

If i am right in every page you include a file in every page that does all the working out, try something like this; it will work based on the page URL.

 

if($_SERVER['SCRIPT_NAME']  == '/news.php') {

    // ... get page titles
    $title = $newsTitle . ' - Latest news from This is Dunstable';

} else {

    $title = 'Dunstable, Bedfordshire - Information, and local resources from This is Dunstable';

}
echo '<title>'.$title.'</title>';

 

There's no information in the page URL which offers a clue to the news item's title, though. If you have a look at http://www.thisisdunstable.co.uk/news.html and click a few headlines, you can see the way it's constructed.

 

Sorry if I misunderstood - I am really quite new to PHP, but have posted the code of both files above in case this helps.

Link to comment
Share on other sites

To get the headline values you can just select the newest. Change the headlineFieldName to the name that the headline field is stored in, change news to the table name and change id to the appropriate field (use a key or date)

 

$result = @mysql_query("SELECT `headlineFieldName` As a FROM `news` ORDER BY `id` DESC LIMIT 1;",$conn) or die('news selection error');
if(@mysql_num_rows($result)) { 

    $newsTitle = mysql_fetch_array($result,MYSQL_ASSOC); $newsTitle =  $newsTitle['a'];
    $title = $newsTitle . ' - Latest news from This is Dunstable';

} else { $newsTitle = 'No News - Latest news from This is Dunstable';

 

There probably is a faster way but this will get the title without having to add them manually.

Link to comment
Share on other sites

To get the headline values you can just select the newest. Change the headlineFieldName to the name that the headline field is stored in, change news to the table name and change id to the appropriate field (use a key or date)

 

$result = @mysql_query("SELECT `headlineFieldName` As a FROM `news` ORDER BY `id` DESC LIMIT 1;",$conn) or die('news selection error');
if(@mysql_num_rows($result)) { 

    $newsTitle = mysql_fetch_array($result,MYSQL_ASSOC); $newsTitle =  $newsTitle['a'];
    $title = $newsTitle . ' - Latest news from This is Dunstable';

} else { $newsTitle = 'No News - Latest news from This is Dunstable';

 

There probably is a faster way but this will get the title without having to add them manually.

 

Thanks for your help on this. Where do I need to place this code? I'm new to PHP and I'm getting stuck trying to follow the instructions you gave.

Link to comment
Share on other sites

<?php
$result = @mysql_query("SELECT `headlineFieldName` As a FROM `news` ORDER BY `id` DESC LIMIT 1;",$conn) or die('news selection error');
if(@mysql_num_rows($result)) { 

    $newsTitle = mysql_fetch_array($result,MYSQL_ASSOC); $newsTitle =  $newsTitle['a'];
    $title = $newsTitle . ' - Latest news from This is Dunstable';

} else { $newsTitle = 'No News - Latest news from This is Dunstable';
?>
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
   <title><?=$newsTitle?></title>
   <meta name="description" content="Dunstable, Bedfordshire - Information, and local resources from This is Dunstable" />
   <meta name="keywords" content="dunstable, bedfordshire" />
   <meta name="Robots" content="index,follow" />
   <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<div id="container">
<?php include("includes/header.shtml"); ?>
<div id="menu-left">
<?php include("includes/menu.shtml"); ?>
</div>
<div id="content">
<h3><span class="green">this</span><span class="grey">is</span><span class="blue">news</span></h3>
<?php include_once("news/easynews.php"); ?>
</div>
<div id="sidebar">
<?php include("includes/sidebar.shtml"); ?>
</div>
<div style="clear:both;"></div>
</div>
<div id="footer"><?php include("includes/footer.shtml"); ?></div>

</body>
</html>

Link to comment
Share on other sites

<?php
$result = @mysql_query("SELECT `headlineFieldName` As a FROM `news` ORDER BY `id` DESC LIMIT 1;",$conn) or die('news selection error');
if(@mysql_num_rows($result)) { 

    $newsTitle = mysql_fetch_array($result,MYSQL_ASSOC); $newsTitle =  $newsTitle['a'];
    $title = $newsTitle . ' - Latest news from This is Dunstable';

} else { $newsTitle = 'No News - Latest news from This is Dunstable';
?>
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
   <title><?=$newsTitle?></title>
   <meta name="description" content="Dunstable, Bedfordshire - Information, and local resources from This is Dunstable" />
   <meta name="keywords" content="dunstable, bedfordshire" />
   <meta name="Robots" content="index,follow" />
   <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<div id="container">
<?php include("includes/header.shtml"); ?>
<div id="menu-left">
<?php include("includes/menu.shtml"); ?>
</div>
<div id="content">
<h3><span class="green">this</span><span class="grey">is</span><span class="blue">news</span></h3>
<?php include_once("news/easynews.php"); ?>
</div>
<div id="sidebar">
<?php include("includes/sidebar.shtml"); ?>
</div>
<div style="clear:both;"></div>
</div>
<div id="footer"><?php include("includes/footer.shtml"); ?></div>

</body>
</html>

 

Hi - Sorry, that doesn't work. I presume it's because the $title variable hasn't been defined yet. If you look at my original code, the PHP is brought in much later, so there's no title for it to grab at that point. This is why I'm getting stuck!  :-\

Link to comment
Share on other sites

It's because the easy news include if after the query and that is where the database connection is, try putting the connection code at the top of the page..

 

Hi,

 

That's still not working. There was a } missing from the PHP code which meant it didn't work, and when I replaced that it gives me a database error now.

 

Would you be willing to take a one-on-one look at it? I'm willing to pay!

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.