?
Solved

commas at address bar

Posted on 2005-04-27
17
Medium Priority
?
653 Views
Last Modified: 2012-06-27
Hi

At some sites, I can see some commas at the address bar. I think they are used to seperate some words. Like "HP,prcgen-GBP240_to_GBP309,_More_than_128MB". Here, by using these three words, it queries the database and get the solutions according to those three. Can you please help me how can I do such a thing?

Kind regards
0
Comment
Question by:hasozduru
17 Comments
 
LVL 27

Expert Comment

by:Diablo84
ID: 13876187
It sounds like you are referring to mod rewriting, which is an Apache module.

Usually it is used to rewrite (for example) urls like:

/thecategory/theitem.html

to:

page.php?category=thecategory&item=theitem

So you can then reference the query string to obtain the values.

But you could write a rule to handle the comma's.

Rewrite rules use the syntax: RewriteRule The_Pattern The_Replacement
The pattern is a regular expression which you would use to match thestring and comma's, you then use back references to handle the replacement.

Below are two links which explain the basics of mod rewriting, they are a good place to start:

http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html
http://www.4webhelp.net/tutorials/misc/mod_rewrite.php

Diablo84
0
 
LVL 20

Expert Comment

by:virmaior
ID: 13876268
1. what is that thing in the address bar:
that's really a rather broad question.  It's hard to know exactly what you're trying to ask.
Basically what you see in the address bar is called a "url" (universal resource locator)
whenever you "go to" a webpage, you are actually sending a request to another computer.  This request is formatted as a URL.

2. what does the thing in the address bar mean:
the web server interprets the URL to determine what it was that you were looking for.  In the context of the web and URLs,  PHP is a server-side programming language that can be set up to handle these requests in conjunction with the web server.  In a URL, the normal way of passing multiple parameters is like this: "mypage.php?&foo=bar&bar=foo"   PHP would interpret this by setting two variables $_GET['foo'] = 'bar'; $_GET['bar'] = 'foo';  
But just because that's the usual way doesn't make it the only way.  experts-exchange for instance takes parameters that look like directory names /Web/Web_Languages/PHP/Q_2140425.html is actually a set of parameters.  These parameters tell the system how to retrieve your question from their database system.  In the example you provided, the parameters are being separated by commas.  This also can be done.  In that case, there are 2 options.   PHP would need to explode the parameters or the webserver would have to translate the page into a different organization.

3. how can PHP understand this style of parameter:
the situation where PHP handles is easier to explain.  If your url was 'mypage.php?i=HP,prcgen-GBP240_to_GBP309,_More_than_128MB'
you would simply explode the $_GET['i'].
<?php
$myparams =  explode(',',$_GET['i']);
echo $myparams[0]; //output is HP
echo $myparams[1]; //output is prcgen-GBP240_to_GBP309
echo $myparams[2]; //output is ,_More_than_128MB
?>

4. How can I use that in a query..
if you wanted to use this in a query you would just amend it to the proper query string
mysql_query('SELECT * FROM mydatabase WHERE chromatype = ' . mysql_real_escape_string($myparams[0]) . ' AND run=' .
mysql_real_escape_string($myparams[1]));

like that

was this helpful?
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13876281
Here is a very basic example for matching 3 numbers separated by commas and ending in .html

RewriteEngine on
RewriteBase /mod_rewrite/
RewriteRule ^([0-9]+),([0-9]+),([0-9]+)\.html$ myfile.php?var1=$1&var2=$2&var3=$3

The above is stored in a .htaccess file.

In this example i have a folder called mod_rewrite which contains the file myfile.php (as well as the .htaccess file). myfile.php simply contains echo $_SERVER['QUERY_STRING'];

Accessing the page via:

http://localhost/mod_rewrite/2321,4142,12.html

results in myfile.php with the output:

var1=2321&var2=4142&var3=12

Diablo84
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Expert Comment

by:designbai
ID: 13876370
using that you can query the database and get the results.

for ex.
querystring = test.php?id=12,23,44,55

using this you can make query,

select * from table where id IN(".$_GET['id'].");

the above fetch all records where id =12 and id=23 and id=44 and id=55.

in case of string you have concatnate with quotes.

hope this helps.
0
 

Author Comment

by:hasozduru
ID: 13876697
Diablo84, thanks for your answers but I am looking for something that designbai and virmaior wrote.

Dear designbai and virmaior

I have a table which has two fields. First one is first_field, second is second_field. I would like to generate a query that queries the table like select * from product where first_field = 1 and second_field = a. At address bar, I have URL like search.php?first_field=1&second_field=a. When you first load the page, imagine links like this:

first field      second field
1                 a
2                 b
3                 c
4                 d

When user clicks to 2, URL will be search.php?first_field=1 and query will be select * from product where first_field = 1
After when user clicks b for example, URL will be search.php?first_field=1&second_field=b and query will be select * from product where first_field = 1 and second_field = b. This can be vice versa as well. I mean user can click to b first, and after 2.

I think you can do it with commas but this can be easier. What would you do?

Thanks
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13876830
Sites that separate parametes with comma's usually do use mod rewriting to keep the url "tidy".

Accessing the page via:

page.php?myvar=var1,var2,var3

wouldn't be very useful as you then have to explode the query string to obtain the relevant pieces of data. I think url encoding *might* have to be handled as well.

If you want 3 separate parameters it's really easier to send them as 3 separate parametes,

page.php?myvar=var1&myvar2=var2&myvar3=var3

Sites that use mod rewriting with comma's are able to use:

/var1,var2,var3.html

and then have it behave the same as page.php?myvar=var1&myvar2=var2&myvar3=var3
but with a much tidier URL.

I don't really see that using a comma as part of a query string variable will serve any real advantage, it has potential for making the user submitted data more difficult to validate (for example, what happens if there is no comma separting your values... you can't explode... so what do you do, you have one piece of data when you was expecting 2).

If your intention is to have a tidier URL, look towards mod rewriting... if it is to make your script more efficient (or anything along those lines) then stick with what you are doing now, keep the parameters separate.

Diablo84
0
 

Author Comment

by:hasozduru
ID: 13952371
Diablo84

Please go to http://dealtime.co.uk/xPP-Personal_Organisers. It says You found over 330 products in Personal Organisers and below that, threre is price range, brand, os etc... I would like to do something like for my site. Please click on Hewlett Packard and see the address bar = http://dealtime.co.uk/xPP-Personal_Organisers--hewlett_packard. After please click to £250-£300 and see the address bar = http://dealtime.co.uk/xPP-Personal_Organisers--hewlett_packard-price_range_250_300. I'd like to do something like this. What would you suggest?

Thanks
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13952531
I would expect they use mod rewriting, or a form of.

The first example would be a fairly simple rule:

RewriteEngine on
RewriteRule ^([A-Za-z]+)--([A-Za-z]+)$ yourpage.php?item=$1&product=$2

Accessing a page via: http://yourdomain.com/theitem-theproduct

would be rewritten as: http://yourdomain.com/yourpage.php?item=theitem&product=theproduct

So you could then reference $_GET['item'] and $_GET['product'].

You could expand this to allow for examples like:

http://dealtime.co.uk/xPP-Personal_Organisers
http://dealtime.co.uk/xPP-Personal_Organisers--hewlett_packard AND
http://dealtime.co.uk/xPP-Personal_Organisers--hewlett_packard-price_range_250_300

Using multiple rules, eg:

RewriteEngine on
RewriteRule ^([A-Za-z]+)-$ yourpage.php?item=$1
RewriteRule ^([A-Za-z]+)--([A-Za-z]+)$ yourpage.php?item=$1&product=$2
RewriteRule ^([A-Za-z]+)--([A-Za-z]+)--([0-9]+)$ yourpage.php?item=$1&product=$2&price=$3

Access via http://yourdomain.com/themaincategory--someproduct--230

Would rewrite as: item=themaincategory&product=someproduct&price=230

These are, of course, very basic examples. In order to make good use of Apaches mod rewriting module you really need to be comfortable working with regular expressions... once you have a good understanding of regex's you will be able to write more complex patterns and have greater control over customizing your URL's.

Diablo84
0
 

Author Comment

by:hasozduru
ID: 13953404
Thanks Diablo84

I need to do that. Where can I find good resource to learn regular expressions. Haven't you got enough information about regular expressions to solve this?

Regards
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13953471
There are many regular expression tutorials online, many of which can be found via Google. One example:

http://gnosis.cx/publish/programming/regular_expressions.html

The basics are as follows:

\  - generally used as an escape character
^  - beginning of string
$  - end of string
.  - used to match any character except new lines
[]  - used to define a character class (eg. [a-z] will match any letter, a through to z)
|  - effectively 'or'
()  - used for a sub pattern to group a match which can be back referenced with $1, $2 etc
?  -  0 or 1 matches, equivalent to {0,1}
*  - 0 or more matches, equivalent to {0,}
+  - 1 or more matches, equivalent to {1,}
{}  - min/max matches (eg: {3,6})

My knowledge of regular expressions is only average because, to date, i have never had a need to extend my ability beyond a basic level. Where PHP is concerned, string functions are generally more efficient then regular expressions, if a problem can be solved with out regex... it should usually be solved without regex. If you are going to be using mod rewriting you need to have a basic understanding of regex. Without this, every time you need to add a rule or modify a pattern you are going to be delayed by having to spending time finding out how to do it. With a basic understanding you will be able to put together simple rules and modify existing ones.

The multiple rules i posted previous will enable you to use a similar system to that used at dealtime.co.uk. Lets take a look at what the third rule means:

RewriteRule ^([A-Za-z]+)--([A-Za-z]+)--([0-9]+)$ yourpage.php?item=$1&product=$2&price=$3

>>>  ^([A-Za-z]+)--([A-Za-z]+)--([0-9]+)$

^  - beginning of the string
([A-Za-z]+)  - a group which matches one or more letters, a through to z and A through to Z
--  - matches --
([A-Za-z]+)  - a group which matches one or more letters, a through to z and A through to Z
--  - matches --
([0-9]+)  - a group which matches one or more numbers, 0 through to 9
$  - end of the string

>>>  yourpage.php?item=$1&product=$2&price=$3

yourpage.php  - begins the rewrite with the url as yourpage.php
?item=$1  - adds to the query string, $1 is a back reference to the first group match ie. ([A-Za-z]+)
&product=$2  - adds to the query string, $2 is a back reference to the second group match ie. ([A-Za-z]+)
&price=$3  - adds to the query string, $3 is a back reference to the third group match ie. ([0-9]+)

So basically, the process is to match the url using groups to define sub patterns, rewrite the url back referencing the sub patterns (thus referencing different parts of the original url) and build them into the query string. You can then take the query string as you would normally and reference each item of the GET array in your page.

Diablo84
0
 

Author Comment

by:hasozduru
ID: 13955553
Diablo84

Thanks for your comments. Actually I need the logic of these links, it doesn't matter the link is like yourpage.php?item=$1&product=$2&price=$3 or dealtime type. I just want to make the link yourpage.php?item=$1&product=$2 and when I click to price for instance, link should be yourpage.php?item=$1&product=$2&price=$3 and query should change according to that.

Thanks
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13955612
It's just a case of referencing the query string, whether url rewriting is used or not the URL will result as yourpage.php?item=$1&product=$2&price=$3 etc.

To reference query string items you use $_GET['name_of_var']

eg. with: yourpage.php?item=anitem&product=aproduct

echo $_GET['item']; //outputs 'anitem'
echo $_GET['product']; //outputs 'aproduct'

You can then use these values and feed them to your query, for example:

$item = mysql_real_escape_string($_GET['item']);
$product = mysql_real_escape_string($_GET['product']);

$query = mysql_query("SELECT * FROM tablename WHERE fieldname = '$item' AND anotherfield = '$product'");

If it is for a search you may wish to also use:

$query = mysql_query("SELECT * FROM tablename WHERE fieldname LIKE '%$item%' AND anotherfield = '%$product%'");
see: http://www.w3schools.com/sql/sql_where.asp

You can then output the results using:

while ($row = mysql_fetch_assoc($query)) {
 //reference $row["fieldname"] for each record where field name is the name of each of the fields
}

As for generating the links, this will be done dynamically when you display the data. You might have a separate table which stores a list of all of the parent categories (which the products table references in a form of ID) so you then loop through each of the items in the table. eg:

while ($row = mysql_fetch_assoc($YOURQUERY)) {
 echo '<a href="searchpage.php?category='.$row['CATEGORY_FIELD'].'">'.$row['CATEGORY_FIELD'].'Link</a>';
}

Then on searchpage.php you have the category selected assigned to $_GET['category'] so you can then run a new query:

$query = mysql_query("SELECT * FROM tablename WHERE category = '{$_GET['category']}'");

The results of which can then be looped through and outputted. Other things like price can be done manually. eg:

<a href="page.php?price=1_100">Between 1 and 100</a>
<a href="page.php?price=101_200">Between 101 and 200</a>
<a href="page.php?price=201_300">Between 201 and 300</a>

Then...

$parts = explode('_',$_GET['price']);
$lowrange = $parts[0]; //eg. 1
$highrange = $parts[1]; //eg. 100

And your query:

"SELECT * FROM tablename WHERE pricefield < '$highrange' AND pricefield > '$lowrange'"

Diablo84
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13955620
You can reference my examples here: http:Q_21412647.html#13928862
for dynamically building a query.
0
 

Author Comment

by:hasozduru
ID: 13955724
Ok

Please see the following code. I managed to write links to the address bar. Please try this code and see how it works. How will be the rest?

Thanks
0
 

Author Comment

by:hasozduru
ID: 13956065
Diablo84

Please see the following code. I managed to do for two fields but I believe code should be written more simpler. If you think to filter for 6-7 specification, this code will be unnecessary long. How would you change the code?

Thanks


<?
include("dbconnect.php");
$URL = $HTTP_SERVER_VARS['REQUEST_URI'];

$sql = mysql_query("select * from spec_palmtop group by first_field");
echo '<table border=1>';
echo '<td><table border=1>';
while ($row = mysql_fetch_object($sql)) {
      $link = "<tr><td><a href=\"" . $URL;
      if(!preg_match("/\?/",$URL))
        $link .="?";
      else
        $link .="&";
      $link .="first_field=" . $row->first_field . "\">$row->first_field</a></td>";
      echo $link;
}

echo '</tr></table>';
$sql2 = mysql_query("select * from spec_palmtop group by second_field");
echo '<td><table border=1>';
while ($row2 = mysql_fetch_object($sql2)) {
      $link = "<tr><td><a href=\"" . $URL;
      if(!preg_match("/\?/",$URL))
        $link .="?";
      else
        $link .="&";
      $link .="second_field=" . $row2->second_field . "\">$row2->second_field</a></td>";
      echo $link;
}

echo '</table>';
echo '</table>';

if($first_field and !$second_field) {
  $q_list = mysql_query("select * from product, spec_palmtop where product.category = 1 and product.product_id = spec_palmtop.product_id and first_field = '$first_field'");
}
elseif (!$first_field and $second_field) {
  $q_list = mysql_query("select * from product, spec_palmtop where product.category = 1 and product.product_id = spec_palmtop.product_id and second_field = '$second_field'");
}
elseif ($first_field and $second_field) {
  $q_list = mysql_query("select * from product, spec_palmtop where product.category = 1 and product.product_id = spec_palmtop.product_id and first_field = '$first_field' and second_field = '$second_field'");
}
else{
  $q_list = mysql_query("select * from product, spec_palmtop where product.category = 1 and product.product_id = spec_palmtop.product_id");
}
while ($q_row = mysql_fetch_object($q_list)) {
      echo "$q_row->p_name<br>";
}

?>
0
 

Author Comment

by:hasozduru
ID: 14090645
Diablo84

Did you check the above example? If not, could you please check?

Regards
0
 
LVL 27

Accepted Solution

by:
Diablo84 earned 2000 total points
ID: 14147211
hasozduru,

My apologies for not replying sooner, i do not appear to have received the notification emails for this thread... it's only lucky that i was looking through the open questions in my comments list and realised that this question was not PAQ'd. Here is one method of tackling this... il mimic the underscore separation method as best as is possible using the query string...

Each parameter will be divided by an underscore and each "slot" will represent a different value, for example:

?data=thecategory_theproduct_thepricerange

in reality this would be, for example:

?data=computermake_computer_0-500

Which would be products under the name of "computer" in the "computermake" category priced between 0 and 500.

I will keep it simple and forus on these three values for now, it can of course be expanded with relative ease.

$data = array();
if (!empty($_GET['data'])) $data = explode('_',$_GET['data']);
$count = count($data);

switch ($count) {
 case 3:
  $query['price'] = $data[2];
 case 2:
  $query['product'] = $data[1];
 case 1:
  $query['category'] = $data[0];
}

The code we have so far, will result in an array of query data depending on the query string, for example:

Page accessed via: thepage.php?data=thecategory
Array Query ( [category] => thecategory )

Page accessed via: thepage.php?data=thecategory_theproduct
Array Query ( [product] => theproduct [category] => thecategory )

Page accessed via: thepage.php?data=thecategory_theproduct_pricerange
Array Query ( [price] => pricerange [product] => theproduct [category] => thecategory )

You can now use this data to build the database queries, for example:

if (!empty($query['price'])) {
 $price = explode('-',$query['price']);
 $result = "SELECT * FROM tablename WHERE categoryfield = '{$query['category']}' AND pricefield > {$price[0]} AND pricefield < {$price[1]}";
}
elseif (!empty($query['product'])) {
 $result = "SELECT * FROM tablename WHERE categoryfield = '{$query['category']}' AND productfield = '{$query['product']}'";
}
elseif (!empty($query['category'])) {
 $result = "SELECT * FROM tablename WHERE categoryfield = '{$query['category']}'";
}
else {
 $result = "SELECT * FROM tablename";
}

$result = mysql_query($result) or die(mysql_error());

you now have the results from the query and can output it or use it as you see fit.

while ($row = mysql_fetch_array($result)) {
 //output data
}

When it comes to actually selecting a specific product i would break away from the underscore approach and use as separate query string variable to avoid unnecessary complication, for example ?productid=theproductid

if (!empty($_GET['productid'])) {
 $query = "SELECT * from tablename WHERE productidfield = '{$_GET['productid']}' LIMIT 1"'
 $query = mysql_query($query) or die(mysql_error());
 //continue to output the corresponding products information
}
else {
 //process search code, maybe display categories etc.
}

My apologies once again for the delayed reply.

Diablo84
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month14 days, 5 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question