I use a Get function to look for the field model
in an url but I have a problem when the model contains a space and a hyphen.
Example: my model in the url is "this-f-example" and the model in the database is "this f-example" (so without the first hyphen).
I wrote the following php code, but it's not sufficient. It would only look for this f example
or this-f-example
in my database so it would return nothing because those models don't exist.
What should I change to my code so it would look for the models this-f example
and this f-example
too?
Complete url: http//:www.example.com/test.php?model=this-f-example
Corresponding model in database: this f-example
<?php
$pdo = new PDO ('mysql:host.....');
$model1 = str_replace ('-', ' ', $_GET['model']);
$model2 = $_GET['model'];
$sql = "SELECT DISTINCT brand, model FROM `exampletable` WHERE model = :model1 OR model = :model2";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":model1", $model1);
$stmt->bindParam(":model2", $model2);
$stmt->execute();
if($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $result['brand'];
echo $result['model'];
}
?>
You could use Regular Expressions.
If the variable
model
that you're sending in url must bethis-f-example
, you could usepreg_replace
instead ofstr_replace
to get yourmodel1
andmodel2
for the model in the url.Try with this code :
But if your problem is just the spaces in your variabale, I think a better solution is to use the
urlencode()
function which will encode the space in your varibale with+
:And when you get it with
$GET['model']
, just use theurldecode()
function to decode the varibale and remove the+
:Hope this could help.