HEYHEY
HEYHEY

Reputation: 533

php dynamic page content based on url

So, there are 3 urls:

example.com/first
example.com/middle
example.com/last

In my sql db, there is table with each terms that correspond to related posts:

ID    NAME    POSTS

1     first   12,3,343
2     middle  23,1,432
3     last    21,43,99

So if an user visits example.com/first, then I want to show posts of "12,3,343" and other posts based on what url they are visiting.

Now, this is the sequence how it would work in my head:

  1. User types "example.com/first"
  2. js (ajax) or something detects the url (in this case, detects "first").
  3. the term is sent to php query.
  4. Gets appropriate info then sends it out (either by ajax or something else).

Am I approaching this right? How does the server detects what url was requested? I supposed I can skip the first two steps if I know how the server detects the url and I can query the correct info directly instead of relying on js to detect it.

Thanks!

Upvotes: 0

Views: 324

Answers (2)

Em Seven
Em Seven

Reputation: 165

When you mention ajax, I assume you are not navigating away from the page your are on. Am I correct?

If so, you have to create another php file to respond to the requests:

  1. A request is sent to file.php with the url as a query string
  2. In file.php, let it query the DB and json_encode the data.
  3. Retrieve the data and update the fields without navigating away.

PHP is only executed once (Server-side). if you want to execute another query you have to either navigate to other URL or just send your request to a php file via ajax.

Upvotes: 2

Sharan Mohandas
Sharan Mohandas

Reputation: 871

You can get the segments of a url request using below statements

$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $url);

Now you have all the segments in an array ($segments) print_r($segments) to get the index of the segment you require.

Now compare that segment with your value For Eg :

if( $segments[2] == 'first')
{
//Your Piece of code
}

Upvotes: 2

Related Questions