How get value from URL [closed]

2019-02-02 18:07发布

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

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

If I open www.example.com/index.php?id=7
get value whose id = 7 in 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;    
}

5条回答
▲ chillily
2楼-- · 2019-02-02 18:19

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'];
查看更多
相关推荐>>
3楼-- · 2019-02-02 18:23

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 = $urlArray[1];
查看更多
啃猪蹄的小仙女
4楼-- · 2019-02-02 18:30

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).

查看更多
你好瞎i
5楼-- · 2019-02-02 18:32

Website URL:

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

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
}
查看更多
叛逆
6楼-- · 2019-02-02 18:38

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']

difference is that variable 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 $_REQUST['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)."'");
查看更多
登录 后发表回答