mySQL query -- if value in string - mysql

I have a string of IDs separated with comma
$myIDs = 22,23,45,895;
How do I write a query to return records for values that correspond to the IDs in my string?
This does not seem to be right:
SELECT *
FROM t1
WHERE itemID IN ($myIDs)
I guess I'm trying PHP array function here, hah? Is there something like this in mySQL?
Appreciate any suggestions. Thanks.

I think you're missing quotes, ie, the exact query should look like this before evaluation
SELECT *
FROM t1
WHERE itemID IN ('22','23','45','895');
Hence all you've got to do to fix this is:-
$myIDs = array(22,23,45,895);
$myIDs_string = "'".implode("','",$myIDs)."'";
then in whatever PHP/SQL library/framework you select, use PHP to execute the following php query:-
SELECT *
FROM t1
WHERE itemID IN ($myIDs_string);
Hope this helps.

$IDs = array(1,2,3,4,5);
// alternatively, you can write it like this...
// $IDs = "1,2,3,4,5";
if(is_array($IDs))
$IDs = implode(",",$IDs);
$query = "SELECT * FROM t1 WHERE itemID IN ($IDs)";
echo $query;

Related

Get results from WPDB

I have this scenario that I can't figure out:
Inside table wp_comment I need to list all user_id (not duplicate) with comment_type=complete.
I tried this:
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'", ARRAY_A );
$corsisti = $results[user_id];
// I need to print only ids to put this array in
get_users( include=> '$corsisti' )
The database screenshot:
You can use the wpdb::get_col() method to retrieve an array with values from a single column:
$corsisti = $GLOBALS['wpdb']->get_col( "SELECT `user_id` FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'");
Then simply use the result in get_users (you do not need the quotes):
$users = get_users( include=> $corsisti );

how to use where clause by sequence of ids

I have a sequence of ids that merged by a comma :
$ids = '1,2,3,4,5,6,7,8,9,10' ;
select * from ads WHERE id = $ids ...
now how can I get content of ads table by these ids ?
You are using PHP. You can build the SQL like this:
$ids = '1,2,3,4,5,6,7,8,9,10';
$sql = 'SELECT * FROM ads WHERE id IN ('.$ids.')';
//execute the query (don't use mysql_* function ;) )
Since MySQL 5.6 you can use FIND_IN_SET() too:
$ids = '1,2,3,4,5,6,7,8,9,10';
$sql = "SELECT * FROM ads WHERE FIND_IN_SET(id, '".$ids."')";
//execute the query (don't use mysql_* function ;) )
Use IN operator
Try this:
SELECT *
FROM ads
WHERE id IN ($ids);

Select Query by array values

I have an array of ids, I have to select from table for each value of array , i can get it by one by one in for loop,
SELECT point, privacy FROM `tableName` WHERE id='1403176452487620892'and status=1
but the problem is that array size is 100, i need a single query not 100.
Why can't you use:
SELECT point, privacy FROM `tableName` WHERE status=1 and id in(?,?,?...)
Yes, it's ridiculously long, but if one query is what you need...
You can use like this :
$ids = join(',',$ids);
$sql = "SELECT * FROM tableName WHERE id IN ($ids)";
You can try like this
$array = array(1,2,3);
$str = implode(",", $array);
$sql = "SELECT point, privacy FROM `tableName` WHERE id in ($str) and status=1";

MYSQL & C#: How to escape the elements in a SELECT WHERE IN (...) clause?

I have procedure with a single string parameter to retrieve records from my table test which has two fields id(int) and Name(varchar).
the query in the procedure is shown below
Select * from test where id in (strParam);
and value in the parameter will be
strParam="1,2";
but the result will be wrong because query will be as shown below
Select * from test where id in ('1,2');
but i need the query to be like shown below
Select * from test where id in (1,2);
please help me with a solution
the programming language is C#
thanks,
suraj
Usually you construct the SQL correctly in your programming language:
Select * from test where id in ('1,2');
should come from your application code, where it's easier to change strParam="1,2"; to strParam="'1','2'":
Split (explode) the string into an array
escape each element in the array (using the correct MySQL-ESCAPE function)
Join (implode) the array back into a string,
If you really can't change the application code, maybe some SQL tricks could work. Try:
SELECT * FROM test where FIND_IN_SET(ID,strParam) > 0
Not sure if this is the most efficient way:
Explode the value strParam to an array and then build up the string you need in the query:
<?php
$arrayParam = explode(',', $strParam);
$strParamQuery = '(';
foreach ($arrayParam as $Param) {
if ($strParamQuery != '(') { $strParamQuery = $strParamQuery.','; //Add a comma to all but the first occurence
$strParamQuery = $strParamQuery.$param;
}
$strParamQuery = $strParamQuery.')';
$query = 'Select * from test where id in '.$strParamQuery.';';
?>

MySQL: How can fetch SUM() of all fields in one Query?

I just want somthing like this:
select SUM(*) from `mytable` group by `year`
any suggestion?
(I am using Zend Framework; if you have a suggestion using ZF rather than pure query would be great!)
Update: I have a mass of columns in table and i do not want to write their name down one by one.
No Idea??
SELECT SUM(column1) + SUM(column2) + SUM(columnN)
FROM mytable
GROUP BY year
Using the Zend Framework's Zend_Db_Select, your query might look like
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from('mytable', array('sum1' => 'SUM(`col1`)', 'sum2' => 'SUM(col2)')
->group('year');
$stmt = $select->query();
$result = $stmt->fetchAll();
Refer to the Zend_Db_Select documentation in the ZF manual for more.
EDIT: My bad, I think I misunderstood your question. The query above will return each colum summed, but not the sum of all of the columns. Rewriting Maxem's query so that you can use it with a Zend Framework DB adapter, it might look like
$sql = '<insert Maxem's query here>';
$result = $db->fetchAll($sql);
You might choose to use fetchCol() to retrieve the single result.
It sounds like you don't want to explicitly enumerate the columnn and that you want to sum all the columns (probably excluding the year column) over all the rows, with grouping by year.
Note that the method Zend_Db_Table::info(Zend_Db_Table_Abstract::COLS) will return an array containing the columns names for the underlying table. You could build your query using that array, something like the following:
Zend_Db_Table::setDefaultAdapter($db);
$table = new Zend_Db_Table('mytable');
$fields = $table->info(Zend_Db_Table_Abstract::COLS);
unset($fields['year']);
$select = $table->select();
$cols = array();
foreach ($fields as $field){
$cols[] = sprintf('SUM(%s)', $field);
}
$select->cols(implode(' + ', $cols));
$select->group('year');
I have not tested the specific syntax, but the core of the idea is the call to info() to get the fields dynamically.
Done in ZF rather than pure query and you don't have to write the name of the columns one by one.
(I assume you are extending Zend_Db_Table_Abstract)
If you're asking how to write
select SUM(*) from `mytable` group by `year`
This is how it is done:
public function sumOfAllFields(){
return $this->fetchAll( $this->select()->from('mytable','SUM(*)')->group('year') )->toArray();
}
Or not using Zend...
function mysql_cols($table){
$sql="SHOW COLUMNS FROM `".$table."`";
$res=mysql_query($sql);
$cols=array();
while($row=mysql_fetch_assoc($res))$cols[]=$row['Field'];
return $cols;
}
$cols=mysql_cols("mytable");
$select_sql=array();
foreach($cols as $col){
$select_sql[]="SUM(`".$col."`)";
}
$select_sql=implode('+',$select_sql);
$sql="select (".$select_sql.") from `mytable` group by `year`";