SQL Query to a Column with ID Numbers Separated by Commas? - php

The Script:
<?php
include("connect.php");
?>
<?php
echo "<h1>The Hashtag: </h1>";
if(isset($_GET['hashtag'])){
echo $_GET['hashtag'];
}
// Select the ID of the given hashtag from the "hashtags" table.
$tqs = "SELECT `id` FROM `hashtags` WHERE `hashtag` = '" . $_GET['hashtag'] . "'";
$tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc));
$row = mysqli_fetch_assoc($tqr);
// This prints e.g.:
// 100
echo "<br/><br/>";
print_r($row['id']);
// Select the threads from the "thread" table which contains the hashtag ID number.
$tqs_two = "SELECT * FROM `thread` WHERE `hashtag_id` IN ('" . $row['id'] . "')";
$tqr_two = mysqli_query($dbc, $tqs_two) or die(mysqli_error($dbc));
$row_two = mysqli_fetch_assoc($tqr_two);
echo "<br/><br/>";
print_r($row_two);
?>
The script should select the rows by that ID number of the hashtag. It should look in the "hashtag_id" column of the table and see if that ID number can be found there, if it can be found there, then it should select that row.
The ID numbers are inside that "hashtag_id" column separated by commas.
Example:
98, 99, 100
Basically, is there a way to do a SQL query to see if the column "contains" that ID number or may have to something else here?
Any suggestions are appreciated.

As Jay says, you can use "contains". You'll need to be cautious though; if you are looking for a hashtag_id of "9", your query needs to avoid returning "19", "99", "93", etc. To that end, you have rely on the exact formatting of the data in that hashtag_id field. If your numbers are really separated by commas and spaces, you can easily find exact matches that ARE NOT AT THE BEGINNING OR END of the query by doing "hashtag_id LIKE '%, 9,'". That won't, however, find any at the beginning or the end of the hashtag_id field. To catch those, you ALSO need "hashtag_id LIKE '9, %'" and "hashtag_id LIKE '%, 9'".
So, to catch all three possibilities:
SELECT * FROM `thread` WHERE `hashtag_id` LIKE '9,%' or `hashtag_id` LIKE '%, 9,%' or `hashtag_id` LIKE '%, 9';

To do contains you would use LIKE -
$tqs_two = "SELECT * FROM `thread` WHERE `hashtag_id` LIKE '%" . $row['id'] . "%'";

Related

Search Each Word Of a Search Using PHP MYSQL Search Query

I want to fetching Records On the Basis Of Entered Keywords in the Search Bar.
Suppose I have Below 3 Records in My SQL Table's Column
Beautiful Small Kid.
Beautiful Rabbit in the Zoo.
Natural Water.
Now, If the Search Query contains Beautiful, It will Return First 2 Records.
If the Search Query contains Beautiful (anything), It will Return Nothing.
I want those First 2 Records to be Displayed in this case too, Because It has the same word beautiful like in above searched Query.
Right Now, I am Using
SELECT * FROM table WHERE name LIKE '%value%' ORDER BY id ASC
Is there any Other Query or Method to Achieve Such Sort Of Results ?
SELECT * FROM table WHERE (name LIKE '%value1%') OR (name LIKE '%value2%') ORDER BY id ASC
etc
So, you would have to split up your search string into separate words.
$str = yourinput;
$strarray = (explode(" ",$str));
$query = "SELECT * FROM table WHERE ";
Foreach($strarray as $key=>$value){
If($key > 0){
$query = $query . "OR";
}
$query = $query . " (name LIKE '%" . $value . "%') ";
}
$query = $query . "ORDER BY id ASC";

MySQL: LIKE and First character

I have two MySQL questions.
$query = " SELECT
stationname
FROM
stations
WHERE
stationname >= '". mysql_real_escape_string($_GET['letter']) ."'
ORDER BY
stationname
";
Here is the first query. In the URL is a parameter set $_GET['letter'] containing an Alphabetic character. I'm trying to select all the rows where stationname starts with $_GET['letter']. So i found this solution in an other Stackoverflow topic, but it doesn't seem to work, i get all my rows, and not just that single one. edit : seems it checks for all the characters in stationname, and not just the starting letter, how can i get that?
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'". mysql_real_escape_string($_POST['search']) ."'
";
Second and final question. I want to make a search engine for my website, selecting all the rows where stationname contains $_POST['search']. But when i have 2 rows, one for example called cheese and the other one called cheese2, and i search for cheese, only cheese get selected, and when i search for cheese2, only cheese2 will get selected. Is there any way to select both cheese and cheese2?
LIKE supports wildcards. % means any number of characters (including zero), and _ means any one character`
stationname LIKE 'cheese%'
This would match cheese and cheese2.
You can use the % for the first issue too.
stationname LIKE 'a%'
This will find all words that start with 'a'.
I'm trying to select all the rows where stationname starts with $_GET['letter']
MySQL has a LEFT function which seems to be what you're looking for. So basically we extract the first letter of the stationname and compare it agains your letter:
where left(stationname, 1) = '" . mysql_real_escape_string($_GET['letter']) . "'";
Is there any way to select both cheese and cheese2?
Well here the solution is a little smelly, as you should check whether cheese is contained in cheese2 and also whether cheese2 is contained in cheese. Try this:
where stationname like '%" . mysql_real_escape_string($_POST['search']) .
"%' OR '" . mysql_real_escape_string($_POST['search']) .
"' like concat('%', stationname, '%')";
for second.
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'". mysql_real_escape_string($_POST['search']) ."%'
";
The text wildcard in MySQL is %, so for your first query you would probably want:
$query = " SELECT
stationname
FROM
stations
WHERE
stationname LIKE '". mysql_real_escape_string($_GET['letter']) ."%'
ORDER BY
stationname
";
And for your second query:
$query = " SELECT
stationname
FROM
stations
WHERE
stationname
LIKE
'%". mysql_real_escape_string($_POST['search']) ."%'
";
FOR Tel Number
5 finds that the first character
$Sql="SELECT * FROM customers WHERE TEL REGEXP '^[5]' LIMIT 0,500";

WHERE IN SQL condition problem

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

MySQL - How to select rows where value is in array?

Ok, normally I know you would do something like this if you knew the array values (1,2,3 in this case):
SELECT * WHERE id IN (1,2,3)
But I don't know the array value, I just know the value I want to find is 'stored' in the array:
SELECT * WHERE 3 IN (ids) // Where 'ids' is an array of values 1,2,3
Which doesn't work. Is there another way to do this?
Use the FIND_IN_SET function:
SELECT t.*
FROM YOUR_TABLE t
WHERE FIND_IN_SET(3, t.ids) > 0
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
If the array element is not integer you can use something like below :
$skus = array('LDRES10','LDRES12','LDRES11'); //sample data
if(!empty($skus)){
$sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "
}
If you use the FIND_IN_SET function:
FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others
AND
FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others
So if record1 is (a,b,c) and record2 is (a)
FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

SQL IN statement and ordering the results

I have a comma delimited list of ids that I want to use to retrieve records from the database. I can use the IN statement to get the results but I want the order of the results to be the same order as the original list.
EG
$list = "3,1,4,2,5";
$query = "SELECT * FROM table WHERE id IN (" . $list . ")";
$result = #mysql_query($query);
while($row=mysql_fetch_array($result)){
echo($row['id']. ", " ); // returns 1, 2, 3, 4, 5
}
OK so I get the results back in the order that they appear in the database - fair enough but I want the results to be in the same order as the original list, I want SQL to retrieve 3 first, then 1 etc...
Is there a SQL command to do this or do I just need to arrange the result the way I need it by some array shuffling? What is the best way to do this?
thanks
$query = "SELECT * FROM table WHERE id IN (" . $list . ") ORDER BY FIND_IN_SET(id, '".$list."')";

Categories