David David - 6 months ago 17
PHP Question

WHERE in SQL request only if(isset($_GET['id'])), else not

I have this request:

$stmt = $pdo->prepare('SELECT id, city, content FROM table WHERE id = :id');
$stmt->execute(array(':city' => $city, ':id' => $id));


And I have this:

if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
[remove this from request: " WHERE id = :id" ];
}


I only want to have
id = :id
in the request
if(isset($_GET['id']))
. Else
id = :id
shouldn't be in the request.

How can I do that?

Greetings,
David.

Answer

Add where-clause to query only when you have $_GET['id']:

$q = 'SELECT id, city, content FROM table WHERE city = :city';
$params = array(':city' => $city);
if (isset($_GET['id'])) {
    $q .= ' AND id = :id';
    $params[":id"] = $_GET['id'];
}
// order by should follow where clause
$q .= ' ORDER BY date_created';

$stmt = $pdo->prepare($q);
$stmt->execute($params);