I'm trying to call a random row from a table where the column "activePages" features a certain id number.
For example, activePages might contain "123 456" on one row, "456 789" on another and I use the following code:
SELECT * FROM advertising WHERE activePages LIKE %456% ORDER BY rand() LIMIT 1
...To call one of those two rows at random.
I want to do this same thing, but with a variable in place of "456". Where do I need to put the % for this to work? Or am I missing another problem entirely?
This is what I have right now:
$getad = $pdo->prepare('SELECT * FROM advertising WHERE activePages LIKE :id ORDER BY rand() LIMIT 1');
$getad->execute(['id' => $id]);
You can use this sort of CONCAT() construct.
WHERE COLUMN LIKE concat('%', :id, '%')
You can put anything you need into CONCAT(), so it's quite flexible.
Wrote a quick test to verify some other posts on SO. Adding the % to the PHP variable works for the like comparison.
<?php
$id = "%" . $searchTerm . "%";
$sql = "SELECT * FROM TABLE
WHERE COLUMN LIKE :id";
$stmt->execute([':id'=> $id]);
?>
Related
I've started developing a project and I need use a advanced search query with PHP and Mysqli, but I'm getting some troubles. Check out below my query.
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE name LIKE '%".$filter."%' OR keybox LIKE '%".$filter."%' ORDER BY id LIMIT 0, 10";
It's working perfeclty! But still not matching entries that contains symbols, for example, if my database contains a row called "Color: red" and someone type "Color red", the query will return empty, but if I type "Color: red" returns found. So, what should I do to resolve this issue?
Thanks
Either use the REGEXP as:-
SELECT * FROM table WHERE columnName REGEXP "regular_expression";
or use REPLACE() function in WHERE clause as:-
SELECT * FROM table WHERE REPLACE(columnName, ":", "") LIKE "like_expression";
The one thing that I can think of in order to maintain consistency is that you can eliminate the ':' in your query for matching. Try the below query:
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE REPLACE(name, ':', '') LIKE '%REPLACE(".$filter.", ':', '')%' OR REPLACE(keybox, ':', '') LIKE '%REPLACE(".$filter.", ':', '')%' ORDER BY id LIMIT 0, 10";
Hope this helps.
Use two queries to find exact and similar records.
If the records available in Exact data query then no need to run the similar data query
<?php
//Fetches Exact Data
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE name LIKE '%".$filter."%' OR keybox LIKE '%".$filter."%' ORDER BY id LIMIT 0, 10";
//If the previous query doesn't return any value, then use
//Split the the user input and then query DB
$condition="name!=''";
$filters=explode(" ",$filter);
foreach($filters as $val)
{
$condition.=" or (name LIKE '%$val%' OR keybox LIKE '%$val%')";
}
//Fetches Similar Data
$query = "SELECT id, name, keybox, posterid, alias, xmdb from `datasys` WHERE $condition ORDER BY id LIMIT 0, 10";
//-----------ENDS
?>
In my table, I have a column that it has a set of users id. its name is users_id.
each id separated with a comma(,).
ex : users_id = '1,2,3,4,5';
if I passed $id=1 to my function, how can I using where statement ?
function($id){
$sql = "select * from content_noti
where ??????"
}
You can add a leading and a trailing , in the field value in DB.
e.g.
Change
1,2,3,4,5
to
,1,2,3,4,5,
So that every Id has leading and trailing comma ,
Now, update the function body:
function($id){
$sql = "select * from content_noti
where users_id LIKE '%,$id,%'"
}
In this case you don't have any possibility of mistake as if you search user id 1 then you will get only 1 and not 11 or 111 or 1343.
Working Demo
if you have multiple ids than it would be better to use IN with query
$sql = "select * from content_noti where id IN (?)"
if you are looking for reverse than use find_in_set
$sql = "select * from content_noti where FIND_IN_SET(?, id)";
You can use regular expressions in mysql:
function($id){
$sql = "SELECT * FROM content_noti WHERE users_id REGEXP '(^|,)" . $i . "($|,)'";
}
SELECT * from content_noti where users_id = "1" OR users_id = LIKE '%1,%' OR users_id = LIKE '%,1%'
Storing multiple chunks of data as a single comma seperated colum is really poor design for databases and if at all possible you should look into normalizing this by making a coupling table and joining on that.
The performance of the above query will be terrible and it'll be hard to maintain.
I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.
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"
);
I have this query:
"SELECT * FROM informations WHERE ". $id ." IN (ids)"
It only works if $id is the first value from ids... in ids values are "1,2,3,4,5".
Is there a way for it to work with the rest of the ids?
Would this work for you?
"SELECT *
FROM Informations
WHERE ids LIKE \"" . $id . ", %\" -- try to match against the first value in ids
OR ids LIKE \"%," . $id . ",%\" -- try to match against a value in ids that is neither the first nor the last value
OR ids LIKE \"%," .$id . "\" -- try to match against the last value found in ids"
If ids is a field containing comma-delimited values, then your query is like:
SELECT * FROM `informations` WHERE 3 IN ("1,2,3,4,5")
Instead of what it should be:
SELECT * FROM `informations` WHERE 3 IN (1,2,3,4,5)
There is no automatic tokenisation (splitting on ,) performed; the one value of ids is not automatically converted into a list for you such that IN can work.
Unfortunately your table design has been your undoing here. Can you split the IDs into a separate table using the principle of database normalisation?
Then your query might look like:
SELECT * FROM `informations` WHERE 3 IN (
SELECT `id`
FROM `ids`
WHERE `informations`.`id` = `ids`.`information_id`
)
BTW, "information" is a non-countable noun and, as such, "informations" is wrong.
Update (thanks for the idea, a1ex07!)
Although this is hackery and I still suggest fixing your table layout, I'll be kind and suggest a quick fix.
Willempie was close with:
$query = 'SELECT *
FROM `informations`
WHERE `ids` LIKE "%' . $id . '%"';
Unfortunately, a wildcard match isn't quite powerful enough. Consider if ids is like "1,6,9,12,35,4" and $id is like 3. You get a false positive. The LIKE statement needs to be aware of the commas.
You can add multiple cases:
$query = 'SELECT *
FROM `informations`
WHERE `ids` LIKE "%,' . $id . ',%"
OR `ids` LIKE "%,' . $id . '"
OR `ids` LIKE "' . $id . ',%"';
Or, for brevity, you can work around this with regular expressions:
$query = 'SELECT *
FROM `informations`
WHERE `ids` REGEXP "(^|,)' . $id . '(,|$)"';
For any $id you wish to find, before it must be the start of ids (^) or a comma; after it must be a comma or the end of ids ($). This ensures that $id must be found as a whole, comma-delimited token.
It's a little like "Whole Word Only" in word processor searches, but with commas separating "words" instead of spaces.
Update 2
Another way uses FIND_IN_SET, which performs a search within a comma-delimited string:
$query = 'SELECT *
FROM `informations`
WHERE FIND_IN_SET("' . $id . '", `ids`)';
Your query is technically correct but the values for 'ids' are not.
You should enclose the values of ids within single quotes. If I were to write the code without using ids, it would be like this:
"SELECT * FROM informations WHERE ". $id ." IN ('1','2','3','4','5')"
More info on this rule here: http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_in
I'm not sure what you are trying to achieve. If ids is a column in informations your code is just a weird way to express "SELECT * FROM informations WHERE ids = ". $id "; If it is a string, I don't see why you need WHERE at all : expression $id in (1,2,3,4,5) is constant, it doesn't require interaction with database; in any case you either grab all rows from informations or none.
UPDATE
Another suggestion :maybe ids is a string field in informations that contains "1,2,3,4,5". In this case you cannot get expected results by using WHERE ... IN. You need to use REGEXP to check if string contains your number.
It has to be column name then IN (comma separated values here).
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
You did an error in sql syntax.
This is the correct syntax
"SELECT * FROM informations WHERE ids IN (". $id .")";