SitePoint Sponsor

User Tag List

Results 1 to 19 of 19
  1. #1
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Trying to store PHP in MySQL

    Okay, this thread may sound convoluted, but here goes...

    My website has different "Sections" (e.g. Finance, Legal, Management, etc.) which you access like this...

    http://local.debbie/finance/

    ...and when you go to that URL, you get a listing of Articles for that Section.

    For each Article, I echo an "Article Summary" that is stored in my database. And because I want to control how each one looks, I decided to just store the HTML in my "summary" field like this...

    <p>Being an entrepreneur and a go getter, a lot of small-business owners want to do it all, however that isn't realistic, especially when it comes to areas like Finance, Marketing, Legal, or I.T. issues.</p><p>First, you run a great risk of really messing up something could jeopardize your finances, your computer systems, or get you into a load of legal trouble. Secondly, even if you could master these areas, you'd be wasting your time that could be better spent growing your business.</p><p>Here are 5 Tips that will help you to know <a href="http://local.debbie/articles/when-to-hire-a-consultant">When to Hire a Consultant</a>
    When I just had one Section called "Articles", this worked fine, but moving forward I want my Article URLs to look like this...

    http://local.debbie/management/articles/when-to-hire-a-consultant


    This creates a few problems...

    1.) The HTML in MySQL is static so there is no easy way to add the "Section".

    2.) I tried adding a PHP Field into the HTML that goes into MySQL, but it isn't working.

    Here s what I did...
    <p>Being an entrepreneur and a go getter, a lot of small-business owners want to do it all, however that isn't realistic, especially when it comes to areas like Finance, Marketing, Legal, or I.T. issues.</p><p>First, you run a great risk of really messing up something could jeopardize your finances, your computer systems, or get you into a load of legal trouble. Secondly, even if you could master these areas, you'd be wasting your time that could be better spent growing your business.</p><p>Here are 5 Tips that will help you to know <a href="http://local.debbie/$section/articles/when-to-hire-a-consultant">When to Hire a Consultant</a>

    And here is the PHP that attempts to echo things...
    PHP Code:
        echo "<div class='articleSummary'>
                <h3>
    $heading</h3>
                <a href=''>
    $image</a>
                <div class='date'>Published: 
    $publishedOn</div>
                
    $summary
            </div>"


    3.) It is likely that I will want to put the "Article Summary" in other sections - to get better exposure - like this...

    http://local.debbie/legal/articles/when-to-hire-a-consultant

    ...so I can't just hard-code in the "Section" to my stored HTML?!


    If I could get my PHP variable to work, then when the HTML is echoed, it would pick up the $section variable and be dynamically populated.

    Any ideas how to do this?

    Thanks,


    Debbie

  2. #2
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Given what you have, I would say you really want to use a placeholder not inject PHP code into MySQL.

    Here is how I've done similar things in the past.
    <p>Being an entrepreneur and a go getter, a lot of small-business owners want to do it all, however that isn't realistic, especially when it comes to areas like Finance, Marketing, Legal, or I.T. issues.</p><p>First, you run a great risk of really messing up something could jeopardize your finances, your computer systems, or get you into a load of legal trouble. Secondly, even if you could master these areas, you'd be wasting your time that could be better spent growing your business.</p><p>Here are 5 Tips that will help you to know <a href="{url}">When to Hire a Consultant</a>
    First thing to notice, is I removed the entire URL from the summary, and replaced it with {url}. I did this for several reasons, 1) it prevents any part of the URL from being "set in stone", and 2) I now have full control over how the URL is generated in my PHP script below.

    The next piece you need is to replace {url} with the actual URL before you output the HTML
    PHP Code:
    $summary $row['summary']; // this should be the column from your MySQL execution to retrieve the summary
    $summary str_replace('{url}'GenerateUrl($row), $summary); // pass whatever variables you need to build the URL
    echo $summary
    Example of GenerateUrl
    PHP Code:
    function GenerateUrl($row)
    {
      
    $url 'http://local.debbie/' $row['section'] . '/articles/' $row['title-slug'];
      return 
    $url;

    Now if your domain ever changes, or your folder hierarchy, you have a way of updating ALL generated URLs at once instead of having to update each one in MySQL.
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  3. #3
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    cpradio,

    Thanks for the response!

    I have to chew on this one for a bit and figure out how to implement it - especially since I exclusively use Prepared Statements.

    On a side note, your response makes it seem like my entire Article table is flawed...

    Here is an example of how I have my Articles stored...

    "article" Table:

    id
    1

    section
    Finance

    slug
    postage-meters-can-save-you-money

    title
    Double Dee: Postage Meters Can Save You Money

    description
    Learn how owning or leasing a Postage Meter can save your small-business both time and money.

    keywords
    Postage Meter

    heading
    Postage Meters Can Save You Money

    subheading
    --

    published on
    2012-01-01 01:00:00

    image
    HTML Code:
    <img class="noborder" src="/images/PostageMeter.png" alt="Picture: Postage Meter.  Credit: John Doe, Wikimedia Commons." title="Picture: Postage Meter.  Credit: John Doe, Wikimedia Commons." />
    summary
    HTML Code:
    <p>When Office Managers are looking for places to save money, postage probably isn't the first thing that comes to mind.  However, just a few trips per week to the Post Office can cost your small-business more in lost productivity and money than you think!</p><p><a href="http://local.debbie/articles/postage-meters-can-save-you-money">Learn how Postage Meters can save you Time & Money</a> and help your business focus on more important issues like growing your business!</p>
    body
    HTML Code:
    <img class="noborder" src="/images/PostageMeter.png" width="170"
    alt="Picture: Postage Meter.  Credit: John Doe, Wikimedia Commons."
    title="Picture: Postage Meter.  Credit: John Doe, Wikimedia Commons." />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus suscipit mattis laoreet. Quisque convallis elementum scelerisque. Nullam accumsan, purus in condimentum placerat, eros lorem pellentesque justo, eget ullamcorper purus felis et magna. Mauris blandit feugiat semper.</p>
    
    <h3>Time is Money!</h3>
    <p>Proin viverra vestibulum velit quis dapibus. Maecenas mattis mauris id eros mollis nec venenatis est faucibus. Maecenas fringilla eleifend tellus, vitae gravida purus rutrum non.</p>
    
    <h3>More Affordable than Appears</h3>
    <p>Vivamus facilisis diam eget nunc ultrices vitae venenatis lorem laoreet. Phasellus aliquet condimentum diam vel feugiat. Quisque dapibus dictum felis, dapibus vestibulum arcu fermentum a. Praesent fringilla sem vitae velit cursus porta. Praesent vitae magna et mi volutpat ultrices a consequat odio.</p>
    
    and so on...
    
    <h3>Next Steps</h3>
    <p>Donec feugiat sollicitudin tristique. Fusce a mauris ante, et semper nibh. Donec nisl libero, imperdiet adipiscing molestie quis, interdum eu tellus. Nunc eu sem elit. Vivamus at massa sit amet mauris blandit ullamcorper a ut magna. Quisque iaculis laoreet lectus vel placerat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla aliquam scelerisque nunc, non facilisis libero ultricies eget. Ut nibh neque, tincidunt vel fermentum vel, faucibus vel erat. In in sapien nec nibh lacinia auctor sit amet eu urna.</p>

    Can you - or others - enlighten me on a better way to store my Articles??


    Here are some Comments/Requirements that might be useful to know...

    1.) Articles are created as follows... I write the Article, then mark it up manually, check how it looks, get it "pixel perfect", and then paste the HTML/Copy into my database via phpMyAdmin.

    2.) Each Article can get formatted and laid out differently, so there is no way - as I see it - to separate the HTM from the Copy

    3.) Each Article can have one or more Pictures/Graphics/Illustrations.

    4.) Each Picture/Graphic/Illustration should be unique to an Article, but it is possible they could get recycled down the road?!

    5.) For each Article, I need different sizes of the same Main Image for the "Article Summary", "Article Body", "Manage Article Subscriptions" pages.
    ---> Do I need to break out the Image info into another table? (Right now, my Images are just in the "images" folder...)

    6.) An Article has a primary "Section" but can be cross-references in other Sections.
    ---> I could create a "Section" and "Article Section" table and do a many-to-many I suppose?!


    Sorry for all of the questions, but my original post is making me see I need a better strategy for my Articles.

    And for what it is worth, I am trying to build a professional-looking online Newspaper/Magazine, which means I am putting a lot more effort into the "Desktop Publishing" area than a typical website.

    Hope you can help.

    Thanks,


    Debbie

  4. #4
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Answering the OP - problem #3: If you want the article to go into different sections, then yes, you will need to look at a one to many database relationship:

    Code:
    articles {
    	id,
    	etc., etc. 	
    }
    
    section {
    	id,
    	name	
    }
    
    ArticleSectionLookup {
    	articleid int, -- references articles.id
    	sectionid int -- references section.id
    }
    Which would (sort of) look like:
    Code:
    articles = {
    	[id: 1, title: Article Title, etc etc]
    }
    
    section = {
    	[id: 1, name: Finance],
    	[id: 2, name: Legal]	
    }
    
    ArticleSectionLookup = {
    	[articleid: 1, sectionid: 1],
    	[articleid: 1, sectionid: 2],	
    }

  5. #5
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    On a side note, your response makes it seem like my entire Article table is flawed...
    Nah, your table isn't flawed (except for item #3, that is flawed, but everything else seems to be fine).

    I like to use WordPress as an example here.

    You will see that apart from your Sections, your table layout is similar to that of WordPress. You will find that WordPress does indeed embed the URL much the way you did. However, there presents the problem (or a problem), in that you can't easily change those URLs later without causing 404s.

    I'm not saying that is the wrong approach, I just like to choose one where I can change the URLs later with ease, versus spending hour upon hour doing it later because I just put the URL in the summary.

    You may even take a slightly changed approach to my first one, so you can link to other articles that may be related.

    You may have a url like so:
    Code:
    <a href="{url}/another-article">text</a>
    Then you would simply use the GenerateUrl to build the domain and section name, but leave the rest of the URL up to the summary text.
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  6. #6
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by cpradio View Post
    Nah, your table isn't flawed (except for item #3, that is flawed, but everything else seems to be fine).
    But your first response should fix that issue, right?



    I like to use WordPress as an example here.

    You will see that apart from your Sections, your table layout is similar to that of WordPress. You will find that WordPress does indeed embed the URL much the way you did. However, there presents the problem (or a problem), in that you can't easily change those URLs later without causing 404s.
    Wow! Comparing my code to WordPress. (I have hit "Rock Bottom" in life now?!)


    I'm not saying that is the wrong approach, I just like to choose one where I can change the URLs later with ease, versus spending hour upon hour doing it later because I just put the URL in the summary.
    Again, your first response to this thread should fix that issue, right?


    You may even take a slightly changed approach to my first one, so you can link to other articles that may be related.

    You may have a url like so:
    Code:
    <a href="{url}/another-article">text</a>
    Then you would simply use the GenerateUrl to build the domain and section name, but leave the rest of the URL up to the summary text.
    I like that idea. (I believe linking and cross-linking within your website is very important to a better User Experience and to getting a better SEO score, right?!)

    BTW, after I typed a book above, I *think* some of this is starting to click. (Too bad it is now the work-week. Hopefully I can keep chipping away at this after work at nights.)

    So, can you offer some advice on how I should handle my Images problem?

    That is, I need 3 different sizes of the "main image" - one for the "Article Summary" (medium), one for the "Article" (large), and possibly one for my "Manage Article Subscriptions" (thumbnail).

    Do I just store one image in my "images" directory and then re-size it as needed?

    Or should I have 3 different sized Images?

    Also, would it be okay to add fields like this to my "article" table...

    image_summary_width
    image_main_width
    image_thumbnail_width

    That way - for each Image - I can grab the Width that I need in different situations - unless I create 3 different sized files, of course.

    Thanks,


    Debbie

  7. #7
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    So, can you offer some advice on how I should handle my Images problem?

    That is, I need 3 different sizes of the "main image" - one for the "Article Summary" (medium), one for the "Article" (large), and possibly one for my "Manage Article Subscriptions" (thumbnail).

    Do I just store one image in my "images" directory and then re-size it as needed?

    Or should I have 3 different sized Images?

    Also, would it be okay to add fields like this to my "article" table...

    image_summary_width
    image_main_width
    image_thumbnail_width

    That way - for each Image - I can grab the Width that I need in different situations - unless I create 3 different sized files, of course.
    I would create three different images, just my opinion. The thought being the smaller images will then load faster due to a very reduced file size from the larger image (might be able to get away with 2 images a medium and large; resizing the medium to the thumbnail size as needed).

    I again divert back to WordPress which creates multiple image sizes upon upload. I've also done this in a variety of situations myself for sites I have built.

    Then reason I compare to WordPress is they have had to take into account a lot of the issues you are facing, starting there isn't a bad thing, can you learn lessons later on that may alter the design (maybe, I don't know what they would be yet, but one day you may find out). You can also compare your setup to other CMSes as well to so how it fairs against what they thought up.
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  8. #8
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    cpradio,

    Based on your advice above, what would you recommend in this scenario...

    In this article...

    http://local.debbie/management/articles/when-to-hire-a-consultant


    ...what if I have a link to this article...

    http://local.debbie/finance/articles/5-tax-shelters-you-need-to-know


    Because the link to the Article "5 Tax Shelter You Need To Know" would in the Article Body which is in MySQL, and because the "Article Section" could change at any time, it couldn't be hard-coded. However, unlike your suggestion above with Article Listing, this would be trickier to build the URL because you couldn't use a generic str_replace with {url} like before.

    I was going to try this...
    PHP Code:
    <a href='{5-tax-shelters-you-need-to-know}'>5 Tax Shelters You Need To Know</a
    ...and then somehow look up the Article Slug, find the Section, and then build the URL, but I am stuck!!

    Any suggestions?

    Thanks,


    Debbie

  9. #9
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    cpradio,

    Based on your advice above, what would you recommend in this scenario...

    In this article...

    http://local.debbie/management/articles/when-to-hire-a-consultant


    ...what if I have a link to this article...

    http://local.debbie/finance/articles/5-tax-shelters-you-need-to-know


    Because the link to the Article "5 Tax Shelter You Need To Know" would in the Article Body which is in MySQL, and because the "Article Section" could change at any time, it couldn't be hard-coded. However, unlike your suggestion above with Article Listing, this would be trickier to build the URL because you couldn't use a generic str_replace with {url} like before.

    I was going to try this...
    PHP Code:
    <a href='{5-tax-shelters-you-need-to-know}'>5 Tax Shelters You Need To Know</a
    ...and then somehow look up the Article Slug, find the Section, and then build the URL, but I am stuck!!

    Any suggestions?

    Thanks,


    Debbie
    The first option I can think of would be to use a similar syntax of {url}, but maybe like so: {url=section;slug}.

    Then the following code would suffice
    PHP Code:
    $matches null;
    if (
    preg_match_all('/\\{url=([a-zA-Z0-9-]+);([a-zA-Z0-9-]+)\\}/'$content$matchesPREG_SET_ORDER) !== false)
    {
      foreach (
    $matches as $match)
      {
        
    $content str_replace($match[0], GenerateLink($match[1], $match[2]), $content); // $match[1] is the slug, $match[2] is the slug
      
    }
    }
    ?> 
    Granted if you ever need to change the slugs, you will have to update the content of your articles, but doing a look up on each embeded URL sounds costly to me. And if you absolutely NEEDED to change a section, you could update your GenerateLink function to replace section "xyz" with "abc" so you don't have to update your content (makes maintenance a bit of a nightmare, but it would work).
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  10. #10
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by cpradio View Post
    doing a look up on each embeded URL sounds costly to me. And if you absolutely NEEDED to change a section, you could update your GenerateLink function to replace section "xyz" with "abc" so you don't have to update your content (makes maintenance a bit of a nightmare, but it would work).
    I don't even necessarily expect every Article to cross-reference other Articles, but the more I do that, the better, right?

    Do you really think it is that "costly" to look up a Referenced Article Slug and build the URL to it? I have lots of scripts that have several calls to my database to build the output, so it doesn't seem like that big of a deal.

    And over the last year when I have been concerned about the same thing, most of the gurus I have spoken to online have told me it is very common to have several queries to look up various data for a script. And that even querying your database for something simple like "Section Display Name" is par for the course...

    Regardless, here is my thinking...

    Let's say I code an "Article Slug" like this...

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque volutpat congue urna, a semper est sollicitudin eget. In quam nulla, porttitor sit amet convallis vitae, faucibus et sapien <a href='{5-tax-shelters-you-need-to-know}'>5 Tax Shelters You Need To Know</a>. Aenean tortor ante, elementum nec volutpat a, pretium ullamcorper lorem...

    Then I could do this...

    1.) Somehow parse out 5-tax-shelters-you-need-to-know
    2.) Use that to look up the "Article Section" in the database
    3.) Use a technique similar to what you originally proposed with generateURL() to create my dynamic URL

    That way, I would always be guaranteed that regardless of how I might re-arrange my Articles, I would always have valid links, right?!

    ----
    Part of what I am trying to do is create a *flexible* framework where I can move Content around anytime I want for maximum exposure and traffic without breaking my website code.

    A common example would be this...

    Let's say I have a new Article that touches some concept in the news (e.g. "Why Minnesota Is Friendly to Small-Businesses"). In that case, I might want to put it in the "In The News" section for the next week, but also put it in its normal place which might be "Start-Ups". Then, as time goes along, I might drop it it from "In The News" and move it to the "Government" section.

    That kind of "plug-and-play" ability would be very powerful from a Content standpoint.

    Still think it is a bad idea from a Technical standpoint?

    Regardless, I think we can agree that hard-coding links is asking for trouble, right?

    Thanks,


    Debbie

  11. #11
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    You can still do the look up if you'd like, just replace my foreach content accordingly, I won't stop you As it will contain the slug and section, you can change it to only have the slug.

    PHP Code:
    $matches null;
    if (
    preg_match_all('/\\{url=([a-zA-Z0-9-]+)\\}/'$content$matchesPREG_SET_ORDER) !== false// matches {url=slug-here}
    {
      foreach (
    $matches as $match)
      {
        
    $content str_replace($match[0], GenerateLink($match[1]), $content); // $match[1] is the slug
      
    }

    If you database is on the same server as your script, then yes the look up may not be too costly, but if it ever isn't (and it shouldn't ever be on the same server as your script from a security standpoint), then you have network latency on all queries and connections, so it "could" be costly.

    Cross linking articles is always a good thing from an SEO standpoint. Hard coding the links "can" be a bad thing, WordPress, Joomla, Drupal, all do it, but if you ever reorganize your data, it is more work for you to do that. Maybe you won't, but until you know how you want it organized, I wouldn't hard code any links until then.
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  12. #12
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by cpradio View Post
    You can still do the look up if you'd like, just replace my foreach content accordingly, I won't stop you As it will contain the slug and section, you can change it to only have the slug.

    PHP Code:
    $matches null;
    if (
    preg_match_all('/\\{url=([a-zA-Z0-9-]+)\\}/'$content$matchesPREG_SET_ORDER) !== false// matches {url=slug-here}
    {
      foreach (
    $matches as $match)
      {
        
    $content str_replace($match[0], GenerateLink($match[1]), $content); // $match[1] is the slug
      
    }

    I'm sorry, but I'm not understanding your code above...

    Your $content would be my entire Article Summary. And the first parameter is saying "One or more of All Letters, Numbers, and Hyphen..." but that makes no sense?!

    As I see it - and I could be way off here - I would want to focus on the "Article Slug" nested in between the { }

    Let's say I have an Article Summary like this...
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque volutpat congue urna, a semper est sollicitudin eget. In quam nulla, porttitor sit amet convallis vitae, faucibus et sapien <a href='{5-tax-shelters-you-need-to-know}'>5 Tax Shelters You Need To Know</a>. Aenean tortor ante, elementum nec volutpat a, pretium ullamcorper lorem.
    Here are my thoughts...

    - Unlike your example directed to my Original Post, we can't search for {url} because the content inside the bracket varies. (In my Article Summary case, I always know the "Section" for each "Article" because I get that as I loop through the Article Records.

    I do NOT have any way of knowing for a given Article what the Related Articles would be, and thus I also don't know what the Related Sections are. There is no concept of "Related Articles" in my "Article" table, although I suppose it is sorta possible. Completely different logic there...)

    - What I DO know is the Article Name (e.g. "5 Tax Shelters You Need To Know") that I want to relate to the Current Article (e.g. "Save Your Taxes for a CPA").

    - I also know that if I know an Article's Slug (e.g. "5-tax-shelters-you-need-to-know"), then I can reverse engineer everything about the Article including the Article's Section (e.g. "Finance").

    Right?

    - If I just searched for { }, then that is too loose. (What happens if I have an Article that uses the brackets in the Article Body?)

    - If I looked for this sub-string...

    <a href='{

    ...then based on what would reasonable be in an Article Body, I know that is the beginning of pseduo-link to another Article

    - So if I could figure out how to tell PHP...

    "Inside the "Article Summary" look for <a href='{, followed by some String (of Letters, Numbers, or a Hyphen), followed by }'>, and if you find that, then copy what is inside the special characters into a variable and then call some Function that will find the Section for that "Article Slug", and finally REPLACE what was originally inside the brackets {} with a new dynamic URL."

    ...then I think I could solve this issue, and have a VERY FLEXIBLE solution!!

    Is that so hard to ask for?!


    I am pretty sure that is how I should solve things - just my opinion - but I don't know how to do this from a programming standpoint.


    If you database is on the same server as your script, then yes the look up may not be too costly, but if it ever isn't (and it shouldn't ever be on the same server as your script from a security standpoint), then you have network latency on all queries and connections, so it "could" be costly.
    Hmmm, that is an intersting comment and probably another thread. (For now, everything will be on one VPS.)


    Cross linking articles is always a good thing from an SEO standpoint. Hard coding the links "can" be a bad thing, WordPress, Joomla, Drupal, all do it, but if you ever reorganize your data, it is more work for you to do that. Maybe you won't, but until you know how you want it organized, I wouldn't hard code any links until then.
    Yep.

    So what do you think about my proposed solution?

    And how can I accomplish it?

    Thanks,


    Debbie

    P.S. I spent this afternoon looking at things like strstr and strpos and so on, but I couldn't find something that translated into what I want to do...

  13. #13
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    I'm sorry, but I'm not understanding your code above...

    Your $content would be my entire Article Summary. And the first parameter is saying "One or more of All Letters, Numbers, and Hyphen..." but that makes no sense?!

    As I see it - and I could be way off here - I would want to focus on the "Article Slug" nested in between the { }
    My recommendation is you can have "{article-slug-here}", or you could use {url=article-slug-here} (in which case, my code would kick right in.

    To use "{article-slug-here}" you would simply just need to remove the url= from my code (as then it will search for letters, numbers and hypens contains in {}. But that does generalize is in that it would catch other {} that may contain letters, numbers and hypens but are not an article slug. However, prefixing article slugs with url= solves that problem (thus back to the original code I posted earlier and makes it very similar to using {url}).

    You won't want to use strpos or strstr, those aren't the right tools for the job (you can do it, it just is far more complicated than using preg_match_all.

    PHP Code:
    $matches null
    if (
    preg_match_all('/\\{([a-zA-Z0-9-]+)\\}/'$content$matchesPREG_SET_ORDER) !== false// matches {slug-here} 

      foreach (
    $matches as $match
      { 
        
    $content str_replace($match[0], GenerateLink($match[1]), $content); // $match[1] is the slug 
      


    Example of usage:
    PHP Code:
    $content_no_prefixes = <<< MY_CONTENT
    This is my fake article <a href="{my-slug-here}">My Slug Here</a> however, I also want to give you a list {1-2-3}, enjoy!
    MY_CONTENT;

    // catching {slug-here}
    $matches_no_prefix null;
    preg_match_all('/\\{([a-zA-Z0-9-]+)\\}/'$content_no_prefixes$matches_no_prefixPREG_SET_ORDER); // matches {slug-here} 
    var_dump($matches_no_prefix);

    $content_prefix = <<< MY_CONTENT_2
    This is my fake article <a href="{url=my-slug-here}">My Slug Here</a> however, I also want to give you a list {1-2-3}, enjoy!
    MY_CONTENT_2;

    // catching {url=slug-here}
    $matches_prefix null;
    preg_match_all('/\\{url=([a-zA-Z0-9-]+)\\}/'$content_prefixes$matches_prefixPREG_SET_ORDER); // matches {url=slug-here} 
    var_dump($matches_prefix); 
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  14. #14
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by cpradio View Post
    My recommendation is you can have "{article-slug-here}", or you could use {url=article-slug-here} (in which case, my code would kick right in.

    To use "{article-slug-here}" you would simply just need to remove the url= from my code (as then it will search for letters, numbers and hypens contains in {}. But that does generalize is in that it would catch other {} that may contain letters, numbers and hypens but are not an article slug. However, prefixing article slugs with url= solves that problem (thus back to the original code I posted earlier and makes it very similar to using {url}).
    Sorry I misunderstood your solution.

    I agree, I like your url= idea better.


    You won't want to use strpos or strstr, those aren't the right tools for the job (you can do it, it just is far more complicated than using preg_match_all.

    PHP Code:
    $matches null
    if (
    preg_match_all('/\\{([a-zA-Z0-9-]+)\\}/'$content$matchesPREG_SET_ORDER) !== false// matches {slug-here} 

      foreach (
    $matches as $match
      { 
        
    $content str_replace($match[0], GenerateLink($match[1]), $content); // $match[1] is the slug 
      


    It is going to take me some time to figure out this code!!!!!!


    Example of usage:
    [php]$content_no_prefixes = <<< MY_CONTENT
    This is my fake article <a href="{my-slug-here}">My Slug Here</a> however, I also want to give you a list {1-2-3}, enjoy!
    MY_CONTENT;
    Do I have to use those funny <<< to make things work??

    Thanks,


    Debbie

  15. #15
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    Do I have to use those funny <<< to make things work??
    LOL, no, that is called HEREDOC syntax and it allows you to quickly create a string with newline characters, variables, etc without having to concatenate strings or escape their values.

    The code you will want is as follows
    PHP Code:
    $matches null;  // will eventually contain the matches to the regular express (in case you cross-link to multiple articles)
    if (preg_match_all('/\\{([a-zA-Z0-9-]+)\\}/'$content$matchesPREG_SET_ORDER) !== false// verify it found at least 1 cross-linked article
    {  
      foreach (
    $matches as $match)  // loop through the cross linked articles
      
    {  
        
    // replace the matching tag {url=article-slug} with the value return from GenerateLink.
        // GenerateLink is passed article-slug as its parameter, so you can query the table and build its URL using the appropriate section
        
    $content str_replace($match[0], GenerateLink($match[1]), $content); 
      }  

    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  16. #16
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Wow!! This is some INTENSE code you are sharing with me...


    Quote Originally Posted by cpradio View Post
    LOL, no, that is called HEREDOC syntax and it allows you to quickly create a string with newline characters, variables, etc without having to concatenate strings or escape their values.
    Oh.


    The code you will want is as follows
    PHP Code:
    $matches null;  // will eventually contain the matches to the regular express (in case you cross-link to multiple articles)
    if (preg_match_all('/\\{([a-zA-Z0-9-]+)\\}/'$content$matchesPREG_SET_ORDER) !== false// verify it found at least 1 cross-linked article
    {  
      foreach (
    $matches as $match)  // loop through the cross linked articles
      
    {  
        
    // replace the matching tag {url=article-slug} with the value return from GenerateLink.
        // GenerateLink is passed article-slug as its parameter, so you can query the table and build its URL using the appropriate section
        
    $content str_replace($match[0], GenerateLink($match[1]), $content); 
      }  


    So I pasted that in a test script and placed in some sample copy and got this for the results...

    Code:
    array
      0 => 
        array
          0 => string '{my-slug-here}' (length=14)
          1 => string 'my-slug-here' (length=12)
      1 => 
        array
          0 => string '{1-2-3}' (length=7)
          1 => string '1-2-3' (length=5)
    
    array
      0 => 
        array
          0 => string '{url=my-slug-here}' (length=18)
          1 => string 'my-slug-here' (length=12)
    
    array
      0 => 
        array
          0 => string '{url=my-slug-here}' (length=18)
          1 => string 'my-slug-here' (length=12)
      1 => 
        array
          0 => string '{url=5-tax-shelters-you-need-to-know}' (length=37)
          1 => string '5-tax-shelters-you-need-to-know' (length=31)
      2 => 
        array
          0 => string '{url=save-your-taxes-for-a-cpa}' (length=31)
          1 => string 'save-your-taxes-for-a-cpa' (length=25)

    Questions:

    1.) Is matches the Outer Array?

    2.) Is match the Inner Array?

    3.) Why do you use preg_match_all vs. preg_match ?

    4.) So I believe this would be saying...

    Take the string save-your-taxes-for-a-cpa and run it through the function GenerateLink and then take the returned value and use it to replace {save-your-taxes-for-a-cpa}
    Sound correct?

    5.) So if I don't use url= then I can have brackets {} in my Articles and not have issues, right?

    6.) It appears that I could have zero, one, or many "Related Article Links" and this code will handle it, right?

    7.) Any Error-Handling or "Gotchas" that I may be forgetting?

    8.) I am hoping that whether I have one all-inclusive Virtual Private Server (VPS), or a VPS Web Server and a separate VPS Database Server, that this solution should be *reasonably* scalable, right?

    I mean, I would say 70% of Articles have no Cross-Reference, and the other 30% that might, would likely only have 1 - maybe 2 - Cross-Links. (Unless I have 500 concurrent Users, I wouldn't think that would be any harder than downloading Article Images, or all of the other things I might query the database for (e.g. User's Name, Username, Section Name, Article Content, etc), right??)

    Thanks a BUNCH for all of the tips!! (I feel like I made a big jump forward to a more sophisticated approach, although I don't have this working yet!!)

    Thanks,


    Debbie

  17. #17
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    Questions:

    1.) Is matches the Outer Array?

    2.) Is match the Inner Array?
    The entire output is $matches (so the outer array)

    [QUOTE=DoubleDee;5196862]3.) Why do you use preg_match_all vs. preg_match ?[/QUOTE

    In case you have multiple links like so
    Code:
      1 => 
        array
          0 => string '{url=5-tax-shelters-you-need-to-know}' (length=37)
          1 => string '5-tax-shelters-you-need-to-know' (length=31)
      2 => 
        array
          0 => string '{url=save-your-taxes-for-a-cpa}' (length=31)
          1 => string 'save-your-taxes-for-a-cpa' (length=25)
    Quote Originally Posted by DoubleDee View Post
    4.) So I believe this would be saying...

    Take the string save-your-taxes-for-a-cpa and run it through the function GenerateLink and then take the returned value and use it to replace {save-your-taxes-for-a-cpa}
    Sound correct?
    Yes

    Quote Originally Posted by DoubleDee View Post
    5.) So if I don't use url= then I can have brackets {} in my Articles and not have issues, right?
    Other way around. If you use url= you can have brackets in your Articles and not have issues. Look at your output again, the first section showed 1-2-3 as being captured, but that wasn't an article slug. The second output does not contain 1-2-3 because it used url= as a prefix to article slugs.

    Quote Originally Posted by DoubleDee View Post
    6.) It appears that I could have zero, one, or many "Related Article Links" and this code will handle it, right?
    Yes, because $matches will become an empty array in this scenario so the foreach will not have anything to loop through.

    Quote Originally Posted by DoubleDee View Post
    7.) Any Error-Handling or "Gotchas" that I may be forgetting?
    Nope

    Quote Originally Posted by DoubleDee View Post
    8.) I am hoping that whether I have one all-inclusive Virtual Private Server (VPS), or a VPS Web Server and a separate VPS Database Server, that this solution should be *reasonably* scalable, right?

    I mean, I would say 70% of Articles have no Cross-Reference, and the other 30% that might, would likely only have 1 - maybe 2 - Cross-Links. (Unless I have 500 concurrent Users, I wouldn't think that would be any harder than downloading Article Images, or all of the other things I might query the database for (e.g. User's Name, Username, Section Name, Article Content, etc), right??)
    This is more of a "wait and see" approach. I can't tell you exactly what kind of network latency you may receive if you have a VPS Web Server and a VPS Database Server (too many variables). My guess is if you are within the same network, you should be fine (meaning both VPS servers are with the same host), but that isn't always true.

    Quote Originally Posted by DoubleDee View Post
    Thanks a BUNCH for all of the tips!! (I feel like I made a big jump forward to a more sophisticated approach, although I don't have this working yet!!)

    Thanks,


    Debbie
    Not a problem.
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  18. #18
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,531
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    cpradio,

    Shouldn't this line in your example...
    PHP Code:
    $matches null;  // will eventually contain the matches to the regular express (in case you cross-link to multiple articles) 

    ...be this instead...
    PHP Code:
    $matches = array;  // will eventually contain the matches to the regular express (in case you cross-link to multiple articles) 

    Debbie

  19. #19
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,827
    Mentioned
    142 Post(s)
    Tagged
    0 Thread(s)
    Doesn't matter, because if the preg_match_all fails (returns FALSE), it will never be used, if the preg_match_all is successful it will either be an empty array or an array with content It just needs to be defined before it is used to avoid a NOTICE: Undeclared variable... yadda yadda yadda
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •