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."')";
Related
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";
I'm trying to query all results where surveyid contains my array $subscibearray. The problem is the SQL query is only returning the first result (44 in this case) instead of all of them. I tried using mysql_fetch_array as well without any success. My results are being outputted via Table. Any help would be appreciated. I omitted as much code as possible to make this easy to read.
Array format:
$subscribearray = "" . join(', ',$subscribearray) . "";
var_dump of $subscribearray:
string(17) "'44, 35, 194, 36'"
query:
$result = mysql_query("SELECT *
FROM surveys
WHERE surveyid IN ($subscribearray)
ORDER BY peercompletetime DESC
LIMIT 100")
or die(mysql_error());
You should:
$subscribearray = join(',', $subscribearray); // 1,2,3
Or:
$subscribearray = "'" . join("','", $subscribearray) . "'"; // '1','2','3'
If you wrap all ids with a string, it will look for the string, and not separated values. ('1,2,3')
Of course, if it's a numeric column you should use the first one.
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'] . "%'";
For fetching some db-posts (int) and then multiplying with user input-values I use php.
$result = mysql_query("SELECT * FROM table")or die("Error" . mysql_error());
while($row = mysql_fetch_array($result)){
$value1=$row['value1'];
$value2=$row['value2'];
$value3=$row['value3'];
$product1=$value1*$userinput1;
$product2=$value2*$userinput2;
$product3=$value3*$userinput3;
}
[Now show results sorted by e.g. product1 ASC]
HOW?
Also how to make it possible to let the user change to e.g. sort by product2?
How can I then show the results, sorted by the sum of the user in put and one value from the row. And also give the user the possibility to change which value and user-input sum to sort by.
mysql_query('SELECT * FROM `table` ORDER BY `value1`*' . intval($userinput) . ' ASC')
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.