I'm making a simple search engine in PHP (with PDO) and MySQL, its goal is to find products in a stock.
My TABLE phone
has a COLUMN snowden
which is a TINYINT
(containing 0
or 1
). I want to be able to get results if phone.snowden
is true
and the user's input is 'snowden'
.
Here's a short version of my query: (:search_0
is the user's input. This is a prepared query for PDO)
SELECT * FROM phone WHERE phone.snowden = 1 AND :search_0 = `snowden`
Of course the real query is actually longer (joining multiple tables and searching into many columns) but everything works except this.
When I try to search 'snowden'
I get no result (meaning the keyword(s) have not been found in any column and the 'snowden' case doesn't work).
- Do I miss something about the syntax ?
- How can I achieve this query in the way I tried ?
- How can I achieve this with a comparison with the column name (if this is a better way to proceed) ?
EDIT: Full code
Here's the full code I use:
$keywords = explode(" ", $_POST['query']);
$query = "SELECT phone.id, phone.imei, phone.model, phone.color, phone.capacity, phone.grade, phone.sourcing, phone.entry, phone.canal, phone.sale, phone.state, phone.snowden FROM phone LEFT JOIN capacity ON (phone.capacity = capacity.id) LEFT JOIN color ON (capacity.color = color.id) LEFT JOIN model ON (color.model = model.id) LEFT JOIN grade ON (phone.grade = grade.id) WHERE ";
$query_array = array();
for ($i = 0; $i < count($keywords); $i += 1) {
$query .= " ( phone.imei LIKE :search_" . $i;
$query .= " OR phone.sourcing LIKE :search_" . $i;
$query .= " OR phone.canal LIKE :search_" . $i;
$query .= " OR phone.entry LIKE :search_" . $i;
$query .= " OR phone.sale LIKE :search_" . $i;
$query .= " OR phone.state LIKE :search_" . $i;
$query .= " OR ( phone.snowden = 1 AND ':search_" . $i . "' = `snowden` )";
$query .= " OR model.name LIKE :search_" . $i;
$query .= " OR color.name LIKE :search_" . $i;
$query .= " OR capacity.amount LIKE :search_" . $i;
$query .= " OR grade.name LIKE :search_" . $i;
if ($i != (count($keywords) - 1)) {
$query .= " ) AND ";
} else {
$query .= " ) ";
}
if (strtolower($keywords[$i]) == 'snowden') {
$query_array['search_' . $i] = $keywords[$i];
} else {
$query_array['search_' . $i] = "%" . $keywords[$i] . "%";
}
}
$query .= "ORDER BY phone.id DESC";
$results = $stock->prepare($query);
$results->execute($query_array);