5

I want to get the value from the URL to choose data from the database by ID. I want the value for the id.

For example, if I were to open www.example.com/index.php?id=12. I want to get a value whose id = 12 in the database.

If I open www.example.com/index.php?id=7.

I want to get the value whose id = 7 in the database and so on.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Vaja Axobadze
  • 75
  • 1
  • 1
  • 7

5 Answers5

20

Website URL:

http://www.example.com/?id=2

Code:

$id = intval($_GET['id']);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Steven
  • 6,053
  • 2
  • 16
  • 28
10

There are two ways to get variable from URL in PHP:

When your URL is: http://www.example.com/index.php?id=7 you can get this id via $_GET['id'] or $_REQUEST['id'] command and store in $id variable.

Lest's take a look:

// url is www.example.com?id=7

//get id from url via $_GET['id'] command:
$id = $_GET['id']

same will be:

//get id from url via $_REQUEST['id'] command:
$id = $_REQUEST['id']

the difference is that variables can be passed to file via URL or via POST method.

if variable is passed through url, then you can get it with $_GET['variable_name'] or $_REQUEST['variable_name'] but if variable is posted, then you need to you $_POST['variable_name'] or $_REQUEST['variable_name']

So as you see $_REQUEST['variable_name'] can be used in both ways.

Dharman
  • 30,962
  • 25
  • 85
  • 135
zur4ik
  • 6,072
  • 9
  • 52
  • 78
  • You still have `$_GET` at your `$_REQUEST` example. Also, if you want to get `GET` data, you should use `$_GET`. This implies that you should never use `$_REQUEST`. – djot Sep 22 '13 at 13:45
  • 1
    @djot agree with you about `GET`. Yes it's always better to use exact method for caching variable, but I just wrote for understanding for @Vaja how variables are sent to file and how they can be cached. – zur4ik Sep 22 '13 at 13:49
  • thanks to all sorry I can't rate all of you but witch was more simple and first thump up it thank you all – Vaja Axobadze Sep 22 '13 at 14:00
1

You can get that value by using the $_GET array. So the id value would be stored in $_GET['id'].

So in your case you could store that value in the $id variable as follows:

$id = $_GET['id'];
SharpKnight
  • 455
  • 2
  • 14
1

You can access those values with the global $_GET variable

//www.example.com/index.php?id=7
print $_GET['id']; // prints "7"

You should check all "incoming" user data - so here, that "id" is an INT. Don't use it directly in your SQL (vulnerable to SQL injections).

djot
  • 2,952
  • 4
  • 19
  • 28
1

You can also get a query string value as:

$uri =  $_SERVER["REQUEST_URI"]; //it will print full url
$uriArray = explode('/', $uri); //convert string into array with explode
$id = $uriArray[1]; //Print first array value
Vignesh V
  • 43
  • 5
Dinesh
  • 4,066
  • 5
  • 21
  • 35