Search code examples
phpgetmysqliseoisset

Replace whitespace with hyphen in URL


I am trying to create a SEO friendly site. At the moment the page works because the id is shown in the URL so like product.php?id=4 however I want to replace ID with the product_name, but the value to this can contain whitespaces, so the URL looks like product.php?product_name=fence%20panel but this doesn't work because I use this GET variable to look up product details in my database, and when it does it thinks it is one word so no product is found. So what I think I need is a variable that adds a hyphen so product.php?product_name=fence-panel but also a variable that changes this hyphen back to a space. Correct me if I'm wrong

if(isset($_GET['id'])){ 
$id = $_GET['id']; 
//Get the product if exists 
//if no product then give a message 
$sql = mysqli_query($myNewConnection, "SELECT * FROM products WHERE id='$id' LIMIT 1"); 
$productCount = mysqli_num_rows($sql); 
if ($productCount > 0) { 
    //get product details 
    while($row = mysqli_fetch_array($sql)){ 
        $product_name = $row["product_name"]; 
        $price = $row["price"]; 
        $details = $row["details"]; 
        $category = $row["category"]; 
        $date_added = strftime("%b %d, %Y", strtotime($row["date_added"])); 
        $_SESSION['product_price_array'] = $price; 
    } 
} else{ 
    echo "No Product in the system"; 
    exit(); 
} 

Solution

  • Use rawurlencode() and rawurldecode(). See the PHP documentation for examples. It won't add hyphens but it will do what you want. To add hyphens you could try doing the following after encoding: $str = str_replace('-', '%2D', $str);. And you should probably do it once again and swap the two first parameters before decoding, too!