SQL - SELECT WHERE column = TRUE AND :input = `string` - php

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

replace your line
$query .= " OR ( phone.snowden = 1 AND ':search_" . $i . "' = `snowden` )";
with
$query .= " OR ( phone.snowden = 1 AND 'snowden'= :search_" . $i )";

Related

single instead of double select statement

first table - bplus - has a column named home01 with values identical to some values in column fname of table banners
$items = '';
$sql = "select home01 from bplus";
$st = $db->query($sql);
$arr = $st->fetchAll(PDO::FETCH_COLUMN);
foreach ($arr as $el){
$el = trim($el);
$sqlb = "select * from banners where fname = '" . $el . "'";
$stb = $db->query($sqlb);
$row = $stb->fetch();
$items .= "<img class='itemtop' src = '../banners/" . $el . "' alt='img' data-id = " . $row['id'] . " data-fname = '" . $row['fname'] . ">\n";
}
echo $items;
this works but probably there is a shorter way, with a single select statement.
Any help?
use LEFT JOIN
select bplus.home01, banners.* from bplus left join banners on bplus.home01 = banners.fname;

Can you use php with an SQL case?

I am trying to optimize some of my code and i believe i need an if/else or case to do this, however I think i would need php in the query to get it to work
here is the code I am trying to optimize
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
GROUP BY age_id; ";
if ($_SESSION['filteryear'] != 0 && $_SESSION['filtermonth'] != 0) {
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
AND year = " . $_SESSION['filteryear'] . " AND month = " . $_SESSION['filtermonth'] . "
GROUP BY age_id; ";
} else if ($_SESSION['filteryear'] != 0 || $_SESSION['filtermonth'] != 0) {
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
AND (year = " . $_SESSION['filteryear'] . " OR month = " . $_SESSION['filtermonth'] . ")
GROUP BY age_id; ";
}
and this is what I have tried to give you a rough idea of what I am trying to achieve
$filter = "";
if ($_SESSION['filteryear'] != 0 && $_SESSION['filtermonth'] != 0) {
$filter = "AND year = " . $_SESSION['filteryear'] . " AND month = " . $_SESSION['filtermonth'] . ""
} else if ($_SESSION['filteryear'] != 0 || $_SESSION['filtermonth'] != 0) {
$filter = "AND (year = " . $_SESSION['filteryear'] . " OR month = " . $_SESSION['filtermonth'] . ")"
}
$sql = "SELECT value, COUNT(*) AS count
FROM sodsurvey LEFT OUTER JOIN age
ON sodsurvey.age_id = age.id
WHERE value IS NOT NULL AND office_id = " . $office_id . "
CASE
WHEN ".isset($filter)." THEN ". $filter ."
END
GROUP BY age_id; ";
You can build up an array of filters depending on which values (year, month, etc) are set, and then combine them all into the WHERE clause. You don't need to worry about all the separate cases where both are set, or one are set, and so on.
I would also strongly echo the advice above that recommended looking into prepared statements, but this will hopefully get you on your way.
<?php
$office_id = 10;
$_SESSION['filteryear'] = 2016;
$_SESSION['filtermonth'] = 12;
$filters = [
"value IS NOT NULL",
"office_id = {$office_id}",
];
if ($_SESSION['filteryear']) {
$filters[] = "year = {$_SESSION['filteryear']}";
}
if ($_SESSION['filtermonth']) {
$filters[] = "month = {$_SESSION['filtermonth']}";
}
$sql = "
SELECT value, COUNT(*) AS count
FROM sodsurvey
LEFT JOIN age ON sodsurvey.age_id = age.id
WHERE " . implode(' AND ', $filters) . "
GROUP BY age_id;
";
The implode line combines each filter that's been set into a single WHERE clause.
is it valid to use PHP with a case in my attempt above?
No. PHP code cannot be part of your SQL query, however your PHP code can generate SQL query
In MySQL, I am trying to find a way to optimize my code
Just make your SQL code generated by PHP code based on all the conditions. You can easily concatenate strings being partions of your query conditionally.

PHP & Mysql Not ordered correctly

I have latest MySQL version (5.5) and this is the screenshot of groupid field
I didn't touch anything yet, but some cells are not ordered correctly like this
But if I click groupid name in the top, it will ordered correctly like this:
Below PHP code output is like first screenshot above, that are not ordered correctly. Please help how to make the output ordered correctly, like it is displayed in the second screenshot above,
Maybe add code like this : order by id asc, but which is the right place to add it below?
$group_ids = explode(" ", $options['groupchoice_ids']);
$groupsql = "SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first = true;
foreach($group_ids as $value)
{
if (!$first)
{
$groupsql = $groupsql . " OR ";
}
else
{
$first = false;
}
$groupsql = $groupsql . " id = '" . $value . "' ";
}
$kh_optionsgroup = '<select name = "accounttype">';
$checksec = $db->query_read($groupsql);
if ($db->num_rows($checksec))
{
while ($lboard = $db->fetch_array($checksec))
{
$kh_optionsgroup = $kh_optionsgroup . "<option value
='" . $lboard['id'] . "'>" . $lboard['title'] . "</option>";
}
}
$verifystring = '$human_verify';
$kh_optionsgroup = $kh_optionsgroup . "</select>";
At the end of your query, you need to set an order, like so:
$groupsql="SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first=true;
foreach($group_ids as $value){
if(!$first){
$groupsql = $groupsql." OR ";
}else{
$first = false;
}
$groupsql = $groupsql." id = '".$value."' ORDER BY groupid ASC";
}
ORDER BY id ASC
This will make the query return its results in ascending order from the groupid column. Simply change ASC to DESC if you want it to go descendinng (high->low).

Displaying Expenses under each expense type using MySQL PDO

I have two tables that I am creating a list that shows all the expenses under each expense type. I have been able to get it to work except when I add the
AND WHERE expenses.pid = " . $pid
it cases a Syntax error and I can't figure out way.
The biggest thing is I need to limet the Expense Type to only show the ones that have some data to go below them
EXPENSETYPE
typeid
pid
exptype
EXPENSES
expid
pid
expdate
checktype
payee
typeid
details
amount
<?php
$pid = 6;
$sql = "SELECT expensetype.typeid, expensetype.exptype
FROM `expensetype` WHERE expensetype.pid = $pid
ORDER BY expensetype.typeid DESC";
$expensetype = $db->query($sql);
foreach($expensetype as $type) {
echo '<li>' . $type['exptype'] . '<ul>';
$sql2 = "SELECT expenses.expid, expenses.expdate, expenses.checktype, expenses.payee, expenses.details, expenses.amount
FROM `expenses` WHERE `expenses`.typeid = " . $type['typeid'] . "AND WHERE expenses.pid = " . $pid ;
$expenses = $db->query($sql2);
foreach($expenses as $exp) {
echo '<li>' . $exp['expdate'] . ' ' . $exp['checktype'] . ' ' . $exp['expdate'] . ' ' . $exp['payee'] . ' ' . $exp['details'] .' ' . $exp['amount'] .'</li>';
}
echo '</ul></li>';
}
?>
Try this SQL statement instead of making two of them :
SELECT `expensetype`.`typeid`, `expensetype.exptype`, `expenses`.`expid`,
`expenses`.`expdate`, `expenses`.`checktype`, `expenses`.`payee`,
`expenses`.`details`, `expenses`.`amount`
FROM `expensetype` INNER JOIN `expenses` ON
`expensetype`.`typeid` = `expense`.`typeid`
WHERE (...)
Also, you cannot use two WHERE in a SQL statement, only use AND.

Error Trying to Use "SET #rownum = 0;" in PHP

When I tested this query out in mysql it was fine but when I went to run it in php I keep getting this 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 'SELECT *, (#rownum := #rownum + 1) AS rank FROM ( SELECT *, (totalWins+(total' at line 1
This is the php code I have.
<?php
$sql = " SET #rownum = 0; ";
$sql .= " SELECT *, (#rownum := #rownum + 1) AS rank FROM ( ";
$sql .= " SELECT *, (totalWins+(totalPushs*.5)) AS totalPoints, totalWins+totalLost+totalPushs AS totalBets FROM ( ";
$sql .= " SELECT *, SUM(win) AS totalWins, SUM(lost) AS totalLost, SUM(push) AS totalPushs FROM ( ";
$sql .= " SELECT *, (finalResult = 'Winner') AS win, (finalResult = 'Loser') AS lost, (finalResult = 'Push') AS push FROM ( ";
$sql .= " SELECT " . $db_prefix . "users.userID, userName, ";
$sql .= " IF (pickID=visitorID, visitorResult, homeResult) AS finalResult ";
$sql .= " FROM " . $db_prefix . "users ";
$sql .= " JOIN " . $db_prefix . "picks ";
$sql .= " ON " . $db_prefix . "users.userID = " . $db_prefix . "picks.userID ";
$sql .= " JOIN " . $db_prefix . "schedule ";
$sql .= " ON " . $db_prefix . "picks.gameID = " . $db_prefix . "schedule.gameID ";
$sql .= " ) x ";
$sql .= " ) x ";
$sql .= " GROUP BY userID ";
$sql .= " ) x ";
$sql .= " ) x ";
$sql .= " ORDER BY totalPoints DESC, totalWins DESC, totalPushs DESC, totalLost ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row[rank] . '|' . $row[userName]. '|' . $row[totalWins] . '|' . $row[totalLost] . '|' . $row[totalPushs] . '|' . $row[totalPoints];
echo '<br>';
}
?>
I can get the php code to work without the first line of code
$sql = " SET #rownum = 0; ";
but it won't echo out the rank column.
Is there something I have to do differently to line one of the code when it's in php?
mysql_query does not support running more than one query at a time. You must first run
mysql_query("SET #rownum = 0;");, then you can run the rest of your query in a second mysql_query call.
Please try tablename.* instead of *

Categories