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.
// turn 'this-f-model' to 'this[- ]f[- ]example'
$model = str_replace ('-', '[- ]', $_GET['model']);
$sql = "SELECT DISTINCT brand, model FROM `exampletable` WHERE model REGEXP :model";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":model", $model);
$stmt->execute();