David David - 1 year ago 76
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
. Else
id = :id
shouldn't be in the request.

How can I do that?


Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download