I want to fetch data from my user table which tag id stored like :
userid tagid
5036 |4815|324|
1396 |1393|4567|
2676 |2669|345|2345|
I have a tagid array like as
Array
(
[0] => 4815
[1] => 4567
)
Need to fetch data using mysql where in condition like "select * from user where tagid in ()".
Is there any preg_match function for it?
Suggest you loop the array and append using likes, something like:
$tags = array(2,4,6);
$query = 'select * from user where ';
foreach($tags as $i=>$tag) {
if ($i>0) $query.=' or '; // or and?
$query.='tagid like "%|'.$tag.'|%"';
}
Because you're having to use a wildcard on both sides of the match they would both be about the same (I think regexp may be a little faster in your case).
The problem is that you may have false positives because of the chance of a substring in your searches because of the lack of normalization.
An example:
Searching for %15%
Matches 915,15,150,215790
Because of this, you should actually do this, since in this case, LIKE would not be sufficient unless you always wrap the IDs in the pipe characters |:
<?php
$ids = array('115','215','225');
foreach($ids as $id){
$query = "select * from user where tagid regexp '[^0-9]*$id[^0-9]*'";
}
?>
At which point you could use this:
<?php
$ids = array('115','215','225');
foreach($ids as $id){
$query = "select * from user where tagid like '%|$id|%'";
}
?>
You can do it like that:
$tagid = array(4815,4567);
$query = "select * from user where tagid regexp '\|("
. implode("|", $tagid) . ")\|'";
then you obtain:
select * from user where tagid regexp '\|(4812|4567)\|'
Related
We have made a search field where you can search for ingredients and find recipes.
For now you can only type in 1 ingredient:
if (isset($_POST['search'])) {
$searchquery = $_POST['search'];
$query = mysql_query("SELECT * FROM opskrifter WHERE id IN
(SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$searchquery'))") or die("search failed");
We want to be able to search for multiple ingredients in the same search field by seperating the ingredients with a "," or something like this.
Is there a simple way to make that happen ?
EDIT:
We tried to use explode like this without succes.
$searchTerms = explode(' ', $searchquery);
$searchTermBits = array();
foreach ($searchTerms as $term) {
if (!empty($term)) {
$searchTermBits[] = "ing_name '$term'";
}}
...
$result = mysql_query("SELECT * FROM opskrifter WHERE id IN (SELECT * FROM WHERE ".implode(' AND ', $searchTermBits)));
Thanks! :)
You could simply get the user to type in his values comma-separated, the the input would be almost in the right syntax for the query. You just have to add semicolons around the values because you search for a string in your table.
You can use PHP's str_replace()-Function:
$vals = $_POST['search'];
$valsFormatted = "'" . str_replace(",", "','", $vals) . "'";
In this code, you replace all the commas of the input with the comma plus semicolons before and behind them in orderto wrap all values of the input with semicolons. You also have to add one at the beginning and at the end of the string. Replace the first comma in the function above with the char you want your users to separate the values with.
After that, you can simply change your query to the following:
$query = "SELECT * FROM opskrifter WHERE id IN
(SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$valsFormatted'))";
Please also be informed, that your code like this is vulnerable for SQL Injections! Check out this link to learn how to prevent this.
A simple statement like this would work:
$array = implode("','",explode($_POST['search'], ","));
$query = mysql_query("SELECT * FROM opskrifter WHERE id IN (SELECT opskrifterid FROM ingredienser WHERE ing_name IN ({$array}))") or die("search failed");
First explode your search, then implode it (might not even need to do so). After that make sure the array gets used as the 'in' operator as a string/array.
For more information about this, you could read this question: PHP/MySQL using an array in WHERE clause
The working copy from my local machine was this;
$_POST['search'] = "0, 1, 2";
$array = implode ( "','", explode ( ",", $_POST['search'] ) );
$query = mysql_query("SELECT * FROM users WHERE id IN ('$array')") or die(mysql_error());
var_dump ( $array );
var_dump ( $query );
var_dump ( "SELECT * FROM users WHERE id IN ('$array')" );
var_dump ( mysql_fetch_array ( $query ) );
which actually did return users, so if we would take this example and change it to your code, it would be (the query, at least):
$query = mysql_query("SELECT * FROM opskrifter WHERE id IN (SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$array'))") or die(mysql_error());
Do take note of the changed $array variable too.
First you need to convert the text coming from the search field to array with:
$string = $_POST['search'];
$array = explode( '"' , $string);
So if you put in the search: test"hello"hi
the array will be:
1 => test,
2 => hello,
3 => hi
After that, you need to use the SQL format:
WHERE column_name IN (value1,value2,...)
So you need to change the array we have created to a string with this format:
$string = implode(',',$array);
So the echo of $string will be:
test,hello,hi
and SQL will be :
WHERE column_name IN ($string)
I have an array lets say: Array ( [0] => 9 [1] => 7 [2] => 8 )
I want to SELECT from a table (users) all phone numbers where userID matches one from the array (if there is a phone number listed).
I want to do this without selecting all of the users from the database and only those that match that of the array and with actual phone numbers, should I do this in a loop?
Typically when I am doing an UPDATE, I do them within a foreach loop. Like so:
foreach($userArr as $user) {
$pid = $user;
if(!$statement->execute()) {
throw new Exception($statement->error, $statement->errno);
}
}
$statement->close();
Can we do SELECT like that as well?
Thanks in advance for any advice.
If you want to select all these users, just do the follow:
$idList = implode(',', $yourArray);
$sql = "SELECT * FROM users WHERE id IN($idList)";
// execute this $sql query
Try this:
<?php
$array = array(9, 7, 8);
$query = "SELECT * FROM mytable WHERE id = ";
$condition = implode(' OR id = ', $array);
$query .= $condition;
echo $query;
?>
Output:
SELECT * FROM mytable WHERE id = 9 OR id = 7 OR id = 8
You should do the following:
Build a string to express the userid seperated by comma. - Loop will be needed. i.e id1, id2, id3
Build the query string to search for them.
Example:
SELECT * FROM `Users` WHERE id IN (id1, id2, id3)
I've researched this but couldn't find a solution for my specific problem.
I have a column containing data in a certain format. Here are some examples:
1
6
14
1;6;14;16
etc...
I need a mysql statement which for example it will select all columns where 16 occurs.
I've tried this but it's also selecting columns where 1 and 6 occur:
"SELECT * FROM tbl WHERE kategorien LIKE '%".$_GET['katid']."%' AND status = 1 ORDER BY pos ASC"
Thanks in advance for any help!
You can try creating a helper function like this:
// Helper function
function getLike($str, $deliminator = ';', $field = 'kategorien') {
if (false !== strpos($str, $deliminator)) {
$strParts = explode($deliminator, $str);
return "($field LIKE '%". implode("%' OR $field LIKE '%", $strParts) . "%')";
} else {
return "$field LIKE '%$str%'";
}
}
// Debug
var_dump(getLike('1;6;14;16'));
Outputs:
string '(kategorien LIKE '%1%' OR kategorien LIKE '%6%' OR kategorien LIKE '%14%' OR kategorien LIKE '%16%')' (length=100)
In your query, you'd use it like this:
"SELECT * FROM tbl WHERE ". getLike($_GET['katid']) ." AND status = 1 ORDER BY pos ASC"
You could use MySQL function FIND_IN_SET:
SELECT * FROM tbl
WHERE
FIND_IN_SET('16', REPLACE(kategorien, ';', ','))>0
however, it is usually not a good idea to store comma separated values in a single field, please have a look at this question: Is storing a delimited list in a database column really that bad?
I am having a small trouble retrieving results that I hope someone can help me with.
I have a field called $incategory which is a comma based string, and what I want to do is explode the into an array that can be used to retrieve results as below (Hope that makes sense):
<?php
$showlist = $row_listelements['incategory'];
// ** e.g. $incategory = 1,3,5,
// ** What I want to do is look at table 'category'
// ** and retrieve results with an 'id' of either 1, 3 or 5
// ** Display Results
mysql_select_db($database_db, $db);
$query_display = "SELECT * FROM category WHERE id = ".$showlist." ORDER BY name ASC";
$display = mysql_query($query_display, $db) or die(mysql_error());
$row_display = mysql_fetch_assoc($display);
$totalRows_display = mysql_num_rows($display);
?>
You can use the IN keyword of SQL directly like this.
query_display = "SELECT * FROM category WHERE id IN (".$showlist.") ORDER BY name ASC";
Another tip would be to stop using MYSQL_QUERY as it is deprecated in PHP 5.3
Edit: If $showlist = '1,3,5,' you will need to remove the last comma from the string to make it useable in the query. Just use this query then
query_display = "SELECT * FROM category WHERE id IN ('".str_replace(",", "','", substr($showlist, -1))."') ORDER BY name ASC";
Use explode function and use , as delimiter.
refer here http://www.w3schools.com/php/func_string_explode.asp
Hope this helps.
First, you have explode the $incategory string into an array containing all of the category number. For example:
$incategory = explode(",", $incategory);
And then you just have to execute this query:
$query_display = "SELECT * FROM category WHERE id = "
. $incategory[$i] . " ORDER BY name ASC";
The $i should be defined beforehand (usually using loop).
The code below only outputs single line(there are 2 in database that should be outputed).
I think that problem is in id=$data[id] since data1 is array instead of single value.I hoped that while will fix that but it doesnt look too good...
$results1 = mysql_query("SELECT * FROM keywords WHERE keyword='$search' ORDER BY (relevant-irrelevant) DESC");
$data1=mysql_fetch_array($results1);
$results2=mysql_query("SELECT * FROM searchengine WHERE id='$data1[id]'");
while($data2=mysql_fetch_array($results2))
First, isolate your ids, looping to get all of the results:
$ids = array();
while ( $data1 = mysql_fetch_array($results1) ) {
$ids[] = $data1['id'];
}
Then, convert your $ids array into a string. An easy way to do this is via implode():
$results2=mysql_query(
"SELECT * FROM searchengine WHERE id IN (" . implode(',', $ids) . ")"
);
Maybe I´m missing something, but how can $data1['id'] be an array? it´s probably an integer and perhaps a string, but it's not an array. $data1['id'] is a single value; the value of field id in the keywords table
I think you just need to put curly quotes around the variable:
$results2=mysql_query("SELECT * FROM searchengine WHERE id='{$data1[id]}'");
or even better:
$results2=mysql_query("SELECT * FROM searchengine WHERE id=" . (int) $data1['id']);
If id is an integer that is.
And of course if the first query returns more than 1 result, you will have to loop through them as well.
Couldn't you just select the entire thing in one query?
SELECT *
FROM keywords k
searchengine s
WHERE k.keyword='$search'
AND k.id = s.id
$results1 = mysql_query("SELECT * FROM keywords WHERE keyword='$search' ORDER BY (relevant-irrelevant) DESC");
$data1=mysql_fetch_array($results1);
//VERY DANGEROUS TO USE USER INPUT
$in = join(',',$data1['id']);
$results2=mysql_query("SELECT * FROM searchengine WHERE id IN ({$in})");
while($data2=mysql_fetch_array($results2))
You can't pass array as condition. You should:
a. do a for(each) loop in the $data1 array and perform next actions
b. implode the array and search with IN. Example:
$commaSeparated = implode(",", $data1);
$results2=mysql_query('SELECT * FROM searchengine WHERE id IN ('.$commaSeparated.'));
mads.ohm is correct about combining the two queries into a single query.
As for your problem with only getting one return value, your while loop is just overwriting the contents of $data2 each time through.
You could write something like this instead:
$i = 0;
$data2 = array();
while ($row = mysql_fetch_array($results2)) {
$data2[$i] = $row;
$i++;
}
In this case, $data2 is declared as an array, and each iteration of the while loop adds a row from the database to the array.