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.
I have some code:
$results = mysql_query("SELECT * FROM next WHERE id=$id");
while ($row = mysql_fetch_array($results))
{
$url = $row['url'];
echo $url;
}
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).
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
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'];
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.
P.S: Also remember - never do like this: $results = mysql_query("SELECT * FROM next WHERE id=$id");
it may cause MySQL Injection and your database can be hacked.
Try to use:
$results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'");
Source: Stackoverflow.com