I have a table with many columns
( A , B , C , D , E)
I have search form and it's works
$query = $pdo->prepare("
SELECT *
FROM Database
WHERE Name LIKE '%{$search}%'
");
On B column I have Names, on A column I have numbers.
I want to search a name from column B and to display it only if A = 0.
SELECT *
FROM Database
WHERE Name LIKE '%{$search}%'
AND A = 0
The SQL query would be the following, using '?' on LIKE to use the prepared statement logic, it is replaced on the next line for the variable $search.
$query = $pdo->prepare("
SELECT *
FROM Database
WHERE B LIKE '%?%' AND A=0
");
$sth->execute(array($search));
Related
I defined a model and tried to get data from two tables using the UNION keyword. Here I used the LIKE keyword as a constraint. When I use this query without variables (hard-coded variable values), it works. But it doesn't work with variables. Instead it gives an empty array. What's wrong with it?
function searchProf(){
//$name=$this->input->post('name');
$name='du';
$query=$this->db->query("SELECT name FROM users WHERE name like '%".$name."%' UNION SELECT name FROM children WHERE name like '%".$name."%' ");
print_r ($query->result());
}
Change '%".$name."%' to this '%$name%'.
function searchProf(){
//$name=$this->input->post('name');
$name ='du';
$query = $this->db->query("SELECT name FROM users WHERE name like '%$name%' UNION SELECT name FROM children WHERE name like '%$name%' ");
print_r ($query->result());
}
Please use active record base or SQL binding to your SQL queries. Otherwise you have to face for SQL Injections.
`
function searchProf(){
$name ='du';
$sql = "SELECT name FROM users WHERE name like ? UNION SELECT name FROM children WHERE name like ? ";
$query = $this->db->query($sql,array('%'.$name.'%','%'.$name.'%'));
print_r ($query->result());
}
I have mysql column called categories. It can contain single or multiple values like this: 1 or 2 or 1,2,3 or 2,12...
I try to get all rows containing value 2.
$query = "SELECT * FROM my_table WHERE categories LIKE '2'";
$rows = mysql_query($query);
This returns row if column only has value 2 but not 1,2,3 or 2,12. How I can get all rows including value 2?
You can use either of the following:
% is a wildcard so it will match 2 or 1,2, etc. Anything on either side of a 2. The problem is it could match 21, 22, etc.
$query = "SELECT * FROM my_table WHERE categories LIKE '%2%'";
Instead you should consider the find_in_set mysql function which expects a comma separated list for the value.
$query = "SELECT * FROM my_table WHERE find_in_set('2', `categories`)";
Like #jitendrapurohut said, you can do it using
$query = "SELECT * FROM my_table WHERE categories LIKE '%2%'";
$rows = mysql_query($query);
But is really bad to store collections like this. A better aproach is as follow:
categories(id_c, name) => A table with each category
my_table(id_m [, ...])
categories_my_table(id_c, id_m)
Then use this query:
SELECT *
FROM my_table m
INNER JOIN categories_my_table cm ON m.id_m = cm.id_m
INNER JOIN categories c ON cm.id_c = c.id_c
WHERE
c.id_c = 2;
EDIT:
#e4c5 link explains why it is bad to store collections like this...
SELECT * FROM my_table WHERE categories LIKE '%2%' AND categories!='1,2,3' AND categories!='2,12';
I have in database two information that matches with the names and the address. Instead of returning 2, this code is returning 21. Please see below;
(Table)-employees
id
name
address
$select = mysql_query("
SELECT *
FROM employees
WHERE name LIKE '%John%'
OR name LIKE '%Johanson%'
AND address='Streetford End'
");
$count = mysql_num_rows($select);
echo $count
This might be helpful:
SELECT * FROM employees WHERE (name LIKE '%John%' OR name LIKE '%Johanson%')
AND address='Streetford End'
I have a somewhat complex query (using a subquery) for an election database where I'm trying to get the number of votes per particular candidate for a position.
The headers for the votes table are: id (PRIMARY KEY), timestamp, pos1, pos2, ..., pos6 where pos1-pos6 are the position names. A cast ballot becomes a new row in this table, with the member id number of the selected candidate (candidates are linked to profiles in a "membership" table in the database) stored as the value for each position. So for instance, one row in the database might look like the following (except with the actual 6 position names):
id timestamp pos1 pos2 pos3 (and so on)
=================================================
6 1386009129 345 162 207
I want to get the results for each position using PHP PDO, listing for each position the candidate's name and the number of votes they have received for this position. So the raw database results should appear as (for "pos1", as an example):
name votecount
======================
Joe Smith 27
Jane Doe 45
I have a raw SQL query which I can successfully use to get these results, the query is (making pos1 the actual column/position name President):
SELECT (SELECT fullname FROM membership memb WHERE member_id=`President`) name, count(`President`) votecount FROM `election_votes` votes GROUP BY `President`
So as you can see, the position name (President, here) is repeated 3 times in the query. This seems to cause a problem in the PHP PDO code. My code is as follows:
$position = "President"; // set in earlier code as part of a loop
$query = "SELECT (SELECT fullname FROM membership memb WHERE member_id=:pos1) name, count(:pos2) votecount FROM `election_votes` votes GROUP BY :pos3";
$query2 = "SELECT (SELECT fullname FROM membership memb WHERE member_id=$position) name, count($position) votecount FROM `election_votes` votes GROUP BY $position"; // NOT SAFE!
$STH = $DBH->prepare($query);
$STH->bindParam(':pos1', $position);
$STH->bindParam(':pos2', $position);
$STH->bindParam(':pos3', $position);
$STH->execute();
while($row = $STH->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
// I'd like to do other things with these results
}
When I run this, using the query $query, I don't get results per-person as desired. My output is:
Array
(
[name] =>
[votecount] => 47
)
where 47 is the total number of ballots cast instead of an array for each candidate contianing their name and number of votes (out of the total). However if I use the obviously insecure $query2, which just inserts the value of $position into the query string three times, I get the results I want.
Is there something wrong with my PHP code above? Am I doing something that's impossible in PDO (I hope not!)? My underlying database is MySQL 5.5.32. I've even tried replacing the three named parameters with the ? unnamed ones and passing an array array($position, $position, $position) into the $STH->execute() method with no greater success.
Your query isn't complex. I think part of the confusion is that you aren't constructing the basic SQL properly. You are attempting to treat "President" as both a value and column. The final SQL should look something like this:
SELECT
`fullname` AS `name`,
COUNT(`id`) AS `votecount`
FROM
`election_votes` AS `votes`
LEFT JOIN
`membership` AS `memb` ON `member_id` = `president`
GROUP BY
`pos1`
You join the election_votes table to the membership table where the value in column pos1 equals the value in column member_id.
NOTE: you cannot use parameters with table and column names in PDO (Can PHP PDO Statements accept the table or column name as parameter?), so you have to escape those manually.
/**
* Map positions/columns manually. Never use user-submitted data for table/column names
*/
$positions = array('President' => 'pos1', 'Vice-president' => 'pos2');
$column = $positions['President'];
You should be able to re-write your query in PDO as:
/**
* Get election results for all candidates
*/
$sql = "SELECT
`fullname` AS `name`,
COUNT(`id`) AS `votecount`
FROM
`election_votes` AS `votes`
LEFT JOIN
`membership` AS `memb` ON `member_id` = `".$column."`
GROUP BY
`".$column."`";
As you can see there's nothing to bind in PDO with this particular query. You use BindParam to filter values that appear in the WHERE clause (again: not table/column names). For example:
/**
* Get election results for person named 'Homer Simpson'
*/
$sql = "SELECT
`fullname` AS `name`,
COUNT(`id`) AS `votecount`
FROM
`election_votes` AS `votes`
LEFT JOIN
`membership` AS `memb` ON `member_id` = `".$column."`
WHERE
`fullname` = :fullname:
GROUP BY
`".$column."`";
$STH = $DBH->prepare($sql);
$STH->bindParam(':fullname', 'Homer Simpson');
This is for an update field and I am checking to be sure the number AND keyword -> OR the campaign name exist to prevent duplicates.
This query is not acting as expected:
$STH = $DBH->prepare("
SELECT *
FROM campaigns
WHERE number = :number AND keyword = :keyword
OR name LIKE :name"
);
I want it to check if (number=number AND keyword=keyword) OR (name=name) - As two different statements not related to eachother. Even if I wrap them in brackets I still get not the right results.
Any help?
LIKE Also needs to have % if it is not supposed to work like = Operator
SELECT * FROM campaigns WHERE (number = :number AND keyword = :keyword) OR name LIKE %:name%"
try it like that
$STH = $DBH->prepare("SELECT *
FROM campaigns
WHERE (number = :number AND keyword = :keyword)
OR name LIKE :name"
);