Question

dynamically populate header meta content with php/mysql

Asked by: nascent1

I want to generate meta tags for my header using info stored in my database. Specifically, I want to be able to pull the title and description info from the table and have that info placed appropriately into the meta tags.

This is the table set up I have:

CREATE TABLE `articles` (
  `id` bigint(24) NOT NULL auto_increment,
  `title` varchar(150) NOT NULL default '',
  `summary` text NOT NULL,
  `description` varchar(100) NOT NULL default '',
  `body` text NOT NULL,
  `parent` bigint(24) NOT NULL default '0',
  `seoname` varchar(150) NOT NULL default '',
  PRIMARY KEY  (`id`),
  KEY `title` (`title`),
  KEY `seoname` (`seoname`),
  KEY `parent` (`parent`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

and this is the portion of my index.php page dealing with the header area:

<?
  include("common.php");
  $mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';

$query = "SELECT *
          FROM articles";
$result = mysql_query($query) or die(mysql_error());
while ($articles = mysql_fetch_object($result)) {
        $title = $articles->title;
            $description = $articles->description;
}
?>

<html>
<head>
<meta name="title" content="<? echo "$title"; ?>">
<meta name="description" content="<? echo "$description"; ?>">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="style.css" rel="stylesheet" type="text/css">

</head>

I have 2 pages set up for testing, each with appropriate info indicating page 1 or page 2, but the code I have above always places the information for page 2 in both page 1's and page 2's meta tags. How can I set this up so that each get their own info?

I'm pretty new at this and hope I've give you all the info you need, but if not, please let me know.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-02-27 at 16:00:13ID21753948
Tags

meta

,

php

,

dynamically

,

header

Topic

Miscellaneous Web Development

Participating Experts
1
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. CSS, PHP and MySQL??
    I have created a css file which contains php, as follows: <style type="text/css"> <!-- <?php include_once("Cconnection.php"); $obconnect = new connect_class(); $obconnect->connection(); $obconnect->dbconnect(); $SQL = "...
  2. PHP, MySQL and IIS6.0 Problem?
    Hi There, We are trying to get a script to run on Windows 2003 IIS 6.0 with PHP and MySQL5. We have a page called index.php, this page has an include and include a file called config.php. If we remove the call to the include the page displays fine. The code in the config.php...
  3. PHP Automated Tooltips with MySQL
    Hi everyone I hope you are all well. Guys i have the following setup. 1 MySQL Table called: tooltip_ttp ------------------------------------------------------------ It has 3 fields, with the following rows currently.. 1) id_ttp (autonum) 2) name_ttp (...
  4. PHP MySql Search
    Hi There, Long time no speak. Hope all is well. I have a small problem I hope you can help me with... I have a MySql database with data. I am looking to write a simple lookup query in php to look up a number (Text Input)-(register no in one of the tables) and if found displa...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: crimson117Posted on 2006-02-27 at 19:33:37ID: 16061831

Don't you need to filter that query so it gets back the information for the correct page?

like

SELECT * FROM Articles WHERE page=1

or

SELECT * FROM Articles WHERE page=2

?

 

by: nascent1Posted on 2006-02-27 at 21:30:03ID: 16062355

Seriously, I don't know <smiles>. I'm hoping that someone knows what is needed to accomplish this.

 

by: crimson117Posted on 2006-02-27 at 22:09:14ID: 16062527

How do you know that you're getting the wrong page's information?

How in the database table does it tell you which information corresponds to which page?

If you put the same exact query at the top of each page, then of course it will return the same information for each page :)

If you filter the query on each page so it only brings back the correct page's info, then you'll only get the correct page's info on each page.

If you know a certain web page corresponds to a certain `id` record in the table, change the code like this:
For page id 1:

$query = "SELECT *
          FROM articles
          WHERE `id` = 1";

For page id 2:

$query = "SELECT *
          FROM articles
          WHERE `id` = 2";


Is that helpful?

 

by: nascent1Posted on 2006-02-28 at 07:26:57ID: 16065984

Crimson117: How do you know that you're getting the wrong page's information?

When I "view source" when the page has been generated, the title and description head tags contain info entered for one of the other pages. (I've tried placing these fields within the body of the page and that works fine with each page's title and description showing appropriately.)

Crimson117: How in the database table does it tell you which information corresponds to which page?

I don't know. Doesn't all the info in one record in the table automatically relate to the one record? In this case, the title, description and body are all in one record. (The body field holds the page content.)

Crimson117: If you put the same exact query at the top of each page, then of course it will return the same information for each page :)

That makes sense <smiles> ... but there is only one index.php that generates each of the pages so I'm not sure how to proceed.


 

by: crimson117Posted on 2006-02-28 at 08:00:41ID: 16066399

You say that the correct bosy information is appearing, but the meta information is always the same.

So it seems that the query that populates the content of the page DOES know exactly which row to choose, while the query that gets the META info DOESN'T know exactly which row to choose.  The body query is probably filtered with "AND id = $some_number"

Can you post the php that gets the body of the page?

 

by: nascent1Posted on 2006-02-28 at 08:38:41ID: 16066786

This is from index.php:

    <p><?=nl2br($page['body'])?></p>

I added the following to the index.php and these do work to pull the content properly from the db to place it in the body:

    <h1><?=$page['title']?></h1>
    <h1><?=$page['description']?></h1>


These are the functions from common.php:

 <?
    session_start();
    include("config.php");
    $dbh=mysql_connect ($dbhost, $dbuser, $dbpassword) or die ('I
cannot connect to the database because: ' . mysql_error());
    mysql_select_db ($dbname,$dbh);
    define("DBH",$dbh);

    function getPage($field='seoname',$value=''){
        $result = mysql_query("SELECT * FROM articles WHERE
{$field}='{$value}'", DBH);
        $page = mysql_fetch_assoc($result);
        return $page;
    }
    function getPages($field='parent',$value='0'){
        $result = mysql_query("SELECT * FROM articles WHERE
{$field}='{$value}'", DBH);
        $pages = array();
        while( $row = mysql_fetch_assoc($result) ){
            $pages[$row['id']] = $row;
        }
        return $pages;
    }
    function AddPage(){
        unset($_POST['id']);
        $_POST['seoname'] = seoname($_POST['title']);
        $query = "INSERT INTO articles (".implode(", ",array_keys
($_POST)).") VALUES ('".implode("', '",array_map
("mysql_real_escape_string",$_POST))."')";
        mysql_query($query,DBH) or die( mysql_error() );
        return mysql_insert_id();
    }
    function UpdatePage($pid){
        $_POST['seoname'] = seoname($_POST['title']);
        $query = "UPDATE articles SET ";
        foreach($_POST as $field => $value) {
        $query .= "$field = '".mysql_real_escape_string
($value)."', ";
        }
        $query = substr($query, 0, strlen($query)-2)." WHERE id =
'{$pid}'";
        mysql_query($query,DBH) or die( mysql_error() );
        return mysql_affected_rows();
    }
    function DeletePage($pid){
        unset($_POST['step']);
        $query = "DELETE FROM articles WHERE id = '{$pid}'";
        mysql_query($query,DBH) or die( mysql_error() );
        return mysql_affected_rows();
    }
    function seoname($string){
        $string = ltrim($string);
        $string = preg_replace( "/ +/", " ", strtolower($string) );
        $string = str_replace(' - ', '-', $string);
        $string = str_replace(array('-
','%',';','/','?',':','@','&','=','+','$',',','#','(',')'), '',
$string);
        $search  = array(' ', 'ä', 'ö',
'ü','ë','ï','é','è','à','ç',);
        $replace = array
('','ae','oe','ue','e','i','e','e','a','c');
        $string = str_replace($search, $replace, $string);
        $string = preg_replace("/[^a-z0-9_-]/", "", $string);
        $string = strtolower($string);
        return urlencode($string);
    }
?>

 

by: crimson117Posted on 2006-02-28 at 09:00:40ID: 16066997

You said "I added the following to the index.php and these do work to pull the content properly from the db to place it in the body:"

So can you put similar values in where you place the meta-tags?  Or does the GetPage function not get executed until later?

 

by: nascent1Posted on 2006-02-28 at 18:18:35ID: 16071762

If I put the following in:


<?
  include("common.php");
  $mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';


?>
<?
$query = "SELECT *
          FROM articles
          WHERE `id` = 1";
  $result = mysql_query($query) or die(mysql_error());
while ($articles = mysql_fetch_object($result)) {
        $title = $articles->title;
$description = $articles->description;
}
?>
<html>
<head>
<meta name="title" content="<? echo "$title"; ?>">
<meta name="description" content="<? echo $description; ?>">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="style.css" rel="stylesheet" type="text/css">

</head>


this is what appears in the head tags:

<html>
<head>
<meta name="title" content="first page title">
<meta name="description" content="first page desc">

and, of course, if I change the id = 1 to id = 2, the info then changes to the page 2 content, which is great. But it remains constant for any page.

You are correct that the page function appears lower in the code.

Do you know if there is a way to change the WHERE portion of the SELECT so that it pulls the data correctly? or am I way off base? <smiles>

Thanks for your interest in this, and for all your help.

 

by: crimson117Posted on 2006-03-01 at 05:49:22ID: 16074807

You'd need to determine what is telling the page which database row's content to display.  

Look for where the "getPage" function is actually called.  What parameters does it use? What determines what values these parameters will be?  Does the user click a link to get to a certain page or something?

 

by: nascent1Posted on 2006-03-01 at 10:47:50ID: 16077802

Problem is now solved <smiles>. I removed the 'select' and added the code that calls the page to the header and it is now working splendidly. Thanks for all your help ... I really appreciate it.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...