简体   繁体   中英

How to rewrite index.php to url in .htaccess

I am trying to create a RESTful web service and having problem with the url part. I this index.php?ID=2 that displays eg

{
"name": "Raymond",
"Nation": "USA"
}

But I want to convert the 'index.php?ID=2' to eg 'localhost/club/player/2/' and still have the same output.

{
 "name": "Raymond",
 "Nation": "USA"
} 

Also lets say I have only 3 rows in my database with ID 1, 2, 3. How do I adjust my code so that when someone used correct ID, Ok 200 message displays or if ID is outside the one in my database error 400 would display.

Here is my code:

$dbhost = '127.0.0.1'; //host connection
$dbuser = "root"; //root connet
$dbpass = ""; //password intialization
$db = 'adminlogin'; //Database specification
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}
$id = $_GET['ID'];
if ($id){
$id = mysqli_real_escape_string($conn, $id);
}  else {
    echo 'no ID';
}
$query = "SELECT Name, Position, Nationality, Market FROM staffdb WHERE ID ='" . $id . "'";
$result = mysqli_query($conn, $query);
if (!$result) {
    printf("Error: %s\n", mysqli_error($conn));
    exit();
}
$temp = array();
if ($result) {
    while ($row = mysqli_fetch_object($result)) {
        $temp = $row;
    }
    header('Content-Type: application/json; charset=UTF-8');
    $json_string = json_encode($temp, JSON_PRETTY_PRINT);
    print $json_string;
} else {
    echo 'no array';
}

Thanks alot!

The Apache module mod_rewrite allows you to rewrite URL requests that come into your server and is based on a regular-expression parser.

You need to put this into .htaccess file

RewriteEngine On 
RewriteRule ^/club/player/([0-9]+)/$ index.php?ID=$1 [L]

I believe that localhost is host name. So you simply skip this from rewrite rule.

You don't need to change anything in your code. Since you pass your variable as ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM