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);
Related
I need to write this query with Doctrine. How can I write it down using QueryBuilder?
SELECT charges.id, charges.currency, charges.total_transactions,
charges.total_volume, charges.commission, refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds
ON charges.id = refunds.id AND charges.currency = refunds.currency
You can use Native SQL and map results to entities:
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:Charges', 'charges')
->addEntityResult('AppBundle:Refunds', 'refunds')
->addFieldResult('charges', 'id', 'id')
->addFieldResult('charges', 'currency', 'currency')
->addFieldResult('charges', 'total_transactions', 'total_transactions')
->addFieldResult('charges', 'total_volume', 'total_volume')
->addFieldResult('charges', 'commission', 'commission')
->addFieldResult('refunds', 'total_payouts', 'total_payouts')
;
$sql = "
SELECT
charges.id,
charges.currency,
charges.total_transactions,
charges.total_volume,
charges.commission,
refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds ON charges.id = refunds.id AND charges.currency = refunds.currency
WHERE some_field = ?
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$entities = $query->getResult();
You can use DQL like this:
$dql = "SELECT ...";
$q = $entityManager->createQuery($dql)->setParameters($arrayParameters);
$result = $q->execute();
or QueryBuilder for each sub-query, like:
// subquery 1
$subQuery1 = $entityManager->createQueryBuilder()
->select('...')
->from('...')
->getDQL()
;
// subquery 2
$subQuery2 = ...
// etc
// ...
// main query
$query = $entityManager->createQueryBuilder()
->select('...')
->from('...', $subQuery1)
->leftJoin('...', $subQuery1->getDQL()),
->where()
;
PS: I just try provide gist for you... hope now you have clue...
Now I found out that it's impossible.
Comment created by stof:
DQL is about querying objects. Supporting subselects in the FROM clause means that the DQL parser is not able to build the result set mapping anymore (as the fields returned by the subquery may not match the object anymore).
This is why it cannot be supported (supporting it only for the case you run the query without the hydration is a no-go IMO as it would mean that the query parsing needs to be dependant of the execution mode).
In your case, the best solution is probably to run a SQL query instead (as you are getting a scalar, you don't need the ORM hydration anyway)
Source: https://github.com/doctrine/doctrine2/issues/3542
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 );
I'm a newbie to mysql, I managed to scrape this together to get the result I wanted. Can it be coded better? Are there any security risks? Its being output in php.
$qwe = $product->virtuemart_product_id;
$id = mysql_real_escape_string($qwe);
$result = mysql_query('SELECT * FROM virtuemart_product_medias where virtuemart_product_id = ' . $id . ' LIMIT 1');
$row = mysql_fetch_assoc($result);
$matched = $row['virtuemart_media_id'];
$result2 = mysql_query('SELECT * FROM virtuemart_medias where virtuemart_media_id = ' . $matched . ' LIMIT 1');
$row2 = mysql_fetch_assoc($result2);
$matched2 = $row2['file_url_thumb'];
echo $matched2;
I don't know whether or not there is a security hole in the specific code you provided - that depends on what other validation exists elsewhere in your program, and what you consider to be a security hole. But the way you are coding means that there definitely could be security holes. Let's look at your first query:
$id = mysql_real_escape_string($qwe);
$result = mysql_query('SELECT *
FROM virtuemart_product_medias
WHERE virtuemart_product_id = ' . $id . ' LIMIT 1');
Imagine if $qwe is the string 0 OR 1=1 --. The mysql_real_escape_string only escapes certain characters such as quotes and backslashes.
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \\, ', " and \x1a.
The string 0 OR 1=1 -- that I mentioned above does not contain any of these characters so it will not be affected at all by mysql_real_escape_string. After you substitute in the value of $id, the resulting SQL query will look something like this:
SELECT *
FROM virtuemart_product_medias
WHERE virtuemart_product_id = 0 OR 1=1 -- LIMIT 1
As you can see, this will return all rows.
Long story short: Use PDO and parameterized queries.
Related
How can I prevent SQL injection in PHP?
Firstly, never use the mysql_* functions. They are deprecated and relying on them is highly discouraged. Use either MySQLi or PDO
The above query could be rewritten as
SELECT file_url_thumb FROM virtuemart_medias where virtuemart_media_id = (SELECT virtuemart_media_id FROM virtuemart_product_medias where virtuemart_product_id = ' . $id . ' LIMIT 1) LIMIT 1
Never do a SELECT *. Include only those fields in your query which you need in your code.
Use one query instead of two, and select only the fields you're using, like so:
SELECT `file_url_thumb` FROM virtuemart_medias where virtuemart_media_id = (SELECT `virtuemart_media_id` FROM virtuemart_product_medias where virtuemart_product_id = ' . $id . ' LIMIT 1) LIMIT 1
You can always use a join;
SELECT a.virtuemart_media_id, b.file_url_thumb
FROM virtuemart_product_medias a
LEFT JOIN virtuemart_medias b
ON a.virtuemart_media_id = b.virtuemart_media_id
WHERE virtuemart_product_id = $id
LIMIT 1
That'll always get you the virtuemart_media_id and, if it exists file_url_thumb.
Your query has a problem also, mysql_real_escape_string only escapes strings, since you're not quoting the $id in the query, it won't be handled as a string and the escaping will not help you. As other replies point out, you should really be using mysqli or PDO.
How about this:
SELECT a.file_url_thumb
FROM virtuemart_medias a
LEFT JOIN virtuemart_product_medias b on a.virtuemart_media_id=b.irtuemart_media_id
WHERE a.virtuemart_product_id=' . $id . ' LIMIT 1
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;
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`";