PHP mysql select query where (wildcard)

♀尐吖头ヾ 提交于 2019-12-11 10:35:34

问题


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


回答1:


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();



回答2:


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";



回答3:


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.




回答4:


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";


来源:https://stackoverflow.com/questions/13773381/php-mysql-select-query-where-wildcard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!