I have an array of ID:s, and the ID:s are in this format:
Bmw_330ci_89492822
So it's a string!
Now, I have this code to find whatever is in that array, in MySQL:
($solr_id_arr is the array I mentioned above, it contains string ID:s)
ex: $solr_id_arr[0] outputs Bmw_330ci_89492822
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Problem is this wont work because (I think) that there should be quotes around each of the imploded elements in order for MySQL to find the match. The field in MySQL I am matching is of type Varchar.
Here is the $query echoed:
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282, Bmw_m5_839493889')
Do you have any other solutions for this, all I need is to find matches in MySQL which are inside this array!
Thanks
Don't surround the entire thing in quotes. It is looking for where ad_id is 'Bmw_m3_cool_565440282, test'
Use
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282', 'test')
A quick fix would be to change:
//this
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
//to this
$solr_id_arr_imploded = implode("', '", $solr_id_arr);
This one seems complicated but it's more safer and fastest one
function escaped($str)
{
return mysql_escape_string($str);
}
$arrayOfIds = array_map("escaped", $solr_id_arr);
$solr_id_arr_imploded = implode(", ", $arrayOfIds);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Simple switch to ', ' in implode():
implode("', '", $solr_id_arr);
This, together with the hardcoded quotes in the SQL string will format them as separate items.
Previous answers will work fine.
Just make sure the strings themselves do not contain quotes. If they do, escape each string before you do the implode().
If it were my code I'd write it like this:
$solr_id_arr_imploded = "'" . implode("', '", $solr_id_arr) . "'";
$query = "SELECT * FROM my_table WHERE ad_id IN ($solr_id_arr_imploded)";
$qry_result = mysql_query($query) or die(mysql_error());
...just because it keeps all the quoting work in one place. You might also want to make sure that the array isn't empty before entering this block of code. Otherwise the SELECT will match all empty ad_id's, which probably isn't what you wanted. We're also assuming that the elements of the array don't include any quote characters (or user-provided strings that haven't been sanity-checked).
Related
I'm trying to create a dynamic code that would ready from any table with the certain name but the difference between each table name is a number that is generated by a variable: for example :
//that's how I get my variable the value for example is = 3
$pid = $GLOBALS["localid"];
//the table name for example is tablename_3
$strTable = "tablename_" .$pid;
//here's how the query should look like
$query = "SELECT * FROM . $strTable . where .....;
I'm making a mistake somewhere but can't figure it out and would appreciate a little help please
Remove the dots and also make sure you have single quotes aroung where
$query = "SELECT * FROM $strTable where '.....';
Besides the comments about do or don't build your queries like this...
You're not closing the quotes properly.
$query = "SELECT * FROM . $strTable . where .....; //Double quote not closed.
should be:
$query = 'SELECT * FROM' . $strTable . 'where .....'; //Single quoted strings concatenated with variable.
or
$query = "SELECT * FROM $strTable where ....."; //Variable inside double quoted string.
I´m trying to put together the most elegant way of searching in two fields for multiple (number of words can vary) terms that needs to only provide results when all words are found (AND instead of OR).
The below gives me an SQL syntax error message:
$search = $_GET["search"];
$searcharray = explode('|', $search);
$query=("SELECT username,sender,message,subject,timestamp,threadid,msgtype
FROM Messages WHERE ('" . implode("'|'",$searcharray) . "') IN CONCAT
(message,subject) ORDER BY timestamp");
I could of course set up a foreach loop for each match on the first word that breaks with an instruction to not add the result if any of the other words are not found in the two fields, but that´s alot more for the PHP script to handle, I think.
Any suggestions?
IN has to be followed by a list of values in parentheses, or a SELECT subquery. You can't use it for pattern matching.
To search a column for a word, you need to use LIKE, with % around the word. And there's no shortcut for searching for multiple words, you have to search for each of them and combine them with AND.
$tests = array_map(function($word) {
return "CONCAT(message, subject) LIKE '%$word%'";
}, $searcharray);
$where = implode(' AND ', $tests);
$query = "SELECT username,sender,message,subject,timestamp,threadid,msgtype
FROM Messages WHERE $where ORDER BY timestamp";
As mentioned in the comments, the code is suseptable to SQL injection. That being said, and since I don't want to re-write all of the code ;-), here's one way to construct the where clause.
$search = $_GET["search"];
$searcharray = explode('|', $search);
$qstr = "SELECT
`username`,
`sender`,
`message`,
`subject`,
`timestamp`,
`threadid`,
`msgtype`
FROM `Messages`
WHERE ";
$w = array();
foreach($searcharray as $key => $val) {
$w[] = "CONCAT(`message`,`subject`) LIKE '%" . $val . "%'";
}
$w_str = implode(" AND ",$w);
$qstr .= $w_str . " ORDER BY `timestamp`";
I have a problem in add value in SELECT query.
$sql=("SELECT `image` FROM `testtable`");
The output: 123.jpg
But I want output: 127.0.0.1/home/galery/123.jpg
So I tried:
$path='127.0.0.1/home/galery/';
.........
$sql=("SELECT $path+`image` FROM `testtable`");
But it's not working.
There are two ways to accomplish this.
Method 1:
Use string concatenation to join the path to the result from the SQL:
$path = '127.0.0.1/home/galery/';
$sql = "SELECT `image` FROM `testtable`";
// Run the query...
$result = $path . $sql;
In php, string concatenation is performed with the . operator. Also see here.
Method 2:
The second method is via the CONCAT SQL function:
$sql = "SELECT CONCAT('" . $path . "', `image`) FROM `testtable`";
Or:
$sql = "SELECT CONCAT('{$path}', `image`) FROM `testtable`";
See this question for the difference between these options.
$sql=("SELECT CONCAT('$path',`image`) FROM `testtable`");
Use concatenation like below....
$sql=("SELECT".$path."+image FROM test")
Here, text in double quotes are string
I have tried this 100 ways and looked all over the net:
<?php
$dbname = 'pdartist2';
$table = 'subcategories';
// query
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = $SCID');
while($row = mysql_fetch_row($result))
{
foreach($row as $cell)
"$cell";
}
mysql_free_result($result);
?>
I am trying to pass the parameter $SCID which is a number, but I can't get the syntax. If I put a number in it works. But I need to be able to pass a variable.
Using single quotes in PHP does not allow variables to be passed through. Make your query line this:
$result = mysql_query("SELECT SubHeaderText FROM subcategories where SCID = $SCID");
you need to use double quotes around the entire query. I have also added error checking as that is very useful to check it worked as expected
$result = mysql_query("SELECT SubHeaderText FROM subcategories where SCID = '$SCID' ") or die(mysql_error());
The two answers given regarding changing single quotes to double quotes are correct, however I have found the best way to accomplish what you are doing is to use single quotes for the sql, then simply append variables to the string, for example:
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = ' . $SCID);
// Or
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = ' . $SCID . ' AND someCol = ' . $someValue);
And as Nick Q. mentioned in a comment, you should prep your variables going into SQL so you don't end up the target of SQL injection attacks. My advice would be to learn PDO where you can prepare your statements then bind values.
The issue is that you're using single quote around your query and PHP won't interpret the variable in single quotes, only in double quotes. So you can write your query in one of two ways.
$result = mysql_query("SELECT SubHeaderText FROM subcategories where SCID = $SCID")
OR
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = '.$SCID)
Using the double quote method can look cleaner, but I personally like using the single quotes with concatenation so my editor will highlight that I'm using a variable there.
I'm trying to build a query using php and mysql,
$query = "select * from products where product_name = '$item_name'";
this works when $item_name holds only one name, but $item_name is an array and based on the user's interaction can contain multiple names, how can I make the query to run for multiple name and get the resulted rows.
Thanks in advance
Here's how you could build a safe list of names for inserting into an IN clause...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
array_map returns the input array of names after running each name through mysql_real_escape_string to sanitize it. We implode that array to make a nice list to use with an IN clause.
You should always ensure any data, particularly coming directly from the client side, is properly escaped in a query to prevent SQL injection attacks.
$vals = implode(',',$item_name);
$query = "select * from products where product_name in (".$vals.");";
Give that a try.
$query = "select * from products where product_name in(";
foreach($item_name as $name)
{
$query .= "'" . $item_name . "', ";
}
$query = substr($query, 0, strlen$query) - 2);
$query .= ");";
First answer (by inkedmn) is really the best one though
foreach($item_name as $name) {
$query = "select * from products where product_name = '$name'";
//whatever you want to do with the query here
}
something like that ought to do it.
Based on inkedmn's response (which didn't quote the item names):
$query = 'select * from products where product_name in ("' . implode('", "', $item_name ) . '")';
Although you may be better with a fulltext search.
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html