How to get value from url

I want to get a value from a URL to select data from a database by ID. I want a value for id.

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

If I open www.example.com/index.php?id=7
get value, id = 7 in the database, etc.

I have a code:

 $results = mysql_query("SELECT * FROM next WHERE id=$id"); while ($row = mysql_fetch_array($results)) { $url = $row['url']; echo $url; } 
+4
source share
5 answers

Site URL:

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

the code:

 $id = intval($_GET['id']); $results = mysql_query("SELECT * FROM next WHERE id=$id"); while ($row = mysql_fetch_array($results)) { $url = $row['url']; echo $url; //Outputs: 2 } 
+10
source

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

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

No need to watch:

 // url is www.example.com?id=7 //get id from url via $_GET['id'] command: $id = $_GET['id'] 

:

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

the difference is that the variable can be transferred to the file by URL or through the POST method.

if the variable is passed via url, you can get it using $_GET['variable_name'] or $_REQUEST['variable_name'] , but if the variable is sent, you need $_POST['variable_name'] or $_REQUST['variable_name']

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

PS: Also remember - never do this: $results = mysql_query("SELECT * FROM next WHERE id=$id"); this can lead to hacking MySQL injection and your database.

Try using:

 $results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'"); 
+7
source

You can get this value using the $_GET array. Thus, the id value will be stored in $_GET['id'] .

So, in your case, you can save this value in the $id variable as follows:

 $id = $_GET['id']; 
0
source

You can access these values ​​using the global variable $ _GET

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

You should check all the "incoming" user data - so here the "id" is INT. Do not use it directly in your SQL (vulnerable to SQL injection).

0
source

You can also get the query string value as:

 $uri = $_SERVER["REQUEST_URI"]; //it will print full url $uriArray = explode('/', $uri); //convert string into array with explode $id = $urlArray[1]; 
0
source

All Articles