I have am trying to use str_replace to read the spaces in “corner tv units” which in my DB and then replace it with a hyphen so I can run a query such as .com/products/corner-tv-units
I have the below code but I am completely new to string replace. Should I be using $name and $query.
$name = str_replace( " ", "-", <%name%>);
$name = mysql_real_escape_string($_GET['name']);
$query = ("
SELECT name, product_id, rrp, discount, image_link
FROM productdbase p
INNER JOIN furniture_groups f
ON
f.long_name = p.furniture_group
WHERE
name LIKE '%{$name}%'
LIMIT 15");
$result = mysql_query($query) or die ("Query: <br>$query<br>Error:<br>".mysql_error());
while ($query_row = mysql_fetch_assoc($result)) {
You can use $name, but it would be like this $name = str_replace(’ ', ‘-’, $query_row[‘name’]);
You can’t simply re-search something like ‘corner-tv-units’ because you have changed the string, you would need to undo it. Something like str_replace(‘-’,’ ', $name);
If you are absolutely sure you can revert a string replace go ahead with it, otherwise a better solution is to have an extra field that holds the rewritten value, so your query would change from name LIKE ‘…’ to url_name = ‘$name’
Most commonly, people will store a “slug” (what we call those hyphenated versions of an item name) in a separate field in the table. This way you don’t really have to str_replace anything at all. Just look up the item by it’s slug. That way both name and slug are available simultaneously.