Reputation: 524
I'm trying to use the following MySQL query, but there is obviously something wrong. I'm trying to make page.php or page.php?q= return the following query:
if (!isset($_GET['q'])) { $where = "WHERE column1 LIKE %"; }
else { $where = "WHERE column1 LIKE ".$_GET['q']; }
$query = "SELECT column1, column2 FROM table '$where' GROUP BY column1";
So if there is no GET, then there is no WHERE
in the MySQL query. I the GET is set to something, then there is a WHERE
with that GET value.
Currently I'm getting the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''WHERE column1LIKE ' GROUP BY column1' at line 1
Upvotes: 1
Views: 2952
Reputation: 2841
For a general solution using PDO, try this snippet (where $db is a PDO connection object).
$params = array();
$sql = 'SELECT column1, column2 FROM table where 1 ';
if (!empty($_GET['q'])) {
$sql .= " column1 like ?";
$params[] = '%' . $_GET['q'] . '%';
}
if (!empty($_GET['r'])) {
$sql .= " column2 like ?";
$params[] = '%' . $_GET['r'] . '%';
}
$sql .= ' GROUP BY column1 ORDER BY column1';
$query = $db->prepare($sql);
$i = 1;
foreach ($params as $param) {
$query->bindValue($i, $param);
$i++;
}
$query->execute();
Upvotes: 1
Reputation: 22977
You need to put the search string in the WHERE
clause between single quotes, like this:
$where = "";
// if there the get q is set we add the were clause
if (!isset($_GET['q'])) {
$where = "WHERE column1 LIKE %";
// ^ This WHERE clause is useless, since it matches all strings.
// Omitting this WHERE clause has the same effect.
}
else { $where = "WHERE column1 LIKE ".$_GET['q']; }
$query = "SELECT column1, column2 FROM table ".$where." GROUP BY column1";
Notice that your script is highly vulnerable agains attacks. Read about SQL-injections.
Upvotes: 1
Reputation: 316
I think you could simply do that: btw.. you do not need the other part "" the like % "" you can simply omit the where clause all together and it will do the same effect... here is a replica of what you just posted:
$where = "";
//if there the get q is set we add the where clause
if(isset($_GET['q'])) {
$where = "WHERE column1 LIKE '".$_GET['q']."'";
}
$query = "SELECT column1, column2 FROM table ".$where." GROUP BY column1";
Upvotes: 0
Reputation: 2418
You need to use some sort of escaping, but that's an exercise for another day. If you simply want to get it working, remove the single quotes around the where variable.
$query = "SELECT column1, column2 FROM table $where GROUP BY column1";
Upvotes: 2