mysql_data_seek not working drupal7 API - drupal

I need to read data twice from query result resource.I had tried with following query but it doesn't work.
$result = db_query("SELECT * FROM test");
echo '<pre>';
print_r($result->fetchAssoc());
mysql_data_seek($result, 0);
print_r($result->fetchAssoc());
Just I tried to iterate result once through $result->fetchAssoc() function again I want iterate record from first row so i used mysql_data_seek but it doesn't work
How do i use mysql_data_seek in drupal7?

Drupal 7 uses PDO so the short answer is you don't use the deprecated mysql_ family of functions anywhere. If you are using those functions, you're doing something wrong.
An equivalent of your code using the Drupal API:
$result = db_query("SELECT * FROM test")->fetchAllAssoc('p_key');
print_r($result[0]);
print_r($result[0]);
See this post for a list of the other helper methods you can use.

Related

Processing Drupal Node Body

I'm new to Drupal. I looked here and on google for a while before asking, but I'm sure I can't find the answer because I don't know how to ask the question.
Here is what's going on. I'm using a custom module to load certain entities and then output them in a specific format for an application to access. The problem is that the NODE BODY contains special information and media files that should be converted. My goal is to obtain the HTML output that would normally be used on this field.
// Execute an EntityFieldQuery
$result = $query->execute();
if (isset($result['node'])) {
$article_items_nids = array_keys($result['node']);
$article_items = entity_load('node', $news_items_nids);
}
// Loop through each article
foreach ($article_items as $article) {
return $article->body[LANGUAGE_NONE]['0']['value'];
}
All of this works great. The only problem is that I get things like this in the output:
[[{"type":"media","view_mode":"media_original","fid":"283","attributes":{"alt":"","class":"media-image","data-thmr":"thmr_32","height":"400","width":"580"}}]]
or
*protoss_icon*
My goal is to find a way that these items are converted just like they are when these articles are viewed normally.
I've tried doing things such as:
render(field_view_field('node', $article, 'body'));
or
render($article->body[LANGUAGE_NONE]['0']['value']);
without success. Thanks for any help, I'm learning so I don't have a complete grasp of the process drupal uses to build output.
You can try something like this (this works only with nodes not with other custom entity types):
$node = node_load($nid);
$field = field_get_items('node', $node, 'your_field_name');
$output = field_view_value('node', $node, 'your_field_name', $field[$delta]);
the field_view_value returns a renderable array for a single field value. (from drupal api documentation)

Generating doctrine slugs manually

I'm using sluggable behavior in my Symfony2 project, but now I would like to make many slugs for one page, based on different texts (current title, old title(s), users text from form input), and keep it in another table. And my question is - how to manually use doctrine extensions for any text? I can't find it anywhere. Perfect would be something like:
/* careful - it's not a real, working code! */
$sluggable = new DoctrineSluggable();
$slug = $sluggable->generate('My own text!');
echo $slug; // my-own-text
I found solution by accident here.
Code:
use Gedmo\Sluggable\Util as Sluggable;
$string = 'My own text!';
$slug = Sluggable\Urlizer::urlize($string, '-');
if(empty($slug)) // if $string is like '=))' or 'トライアングル・サービス' an empty slug will be returned, that causes troubles and throws no exception
echo 'error, empty slug!!!';
else
echo $slug;
Find the doctrine code for generating a slug here: l3pp4rd/DoctrineExtensions. Playing around with that class could do as you desire but you will probable need to create your own service to implement an easy use as you want. See the Service Container section of the docs for more details about services.
The Sluggable\Urlizer::urlize seems to replace ' with -.
I had to use Sluggable\Urlizer::transliterate to be closer to the SluggableListener behaviour.

Drupal: hook_search only for a content type

I would like to build a custom search module in Drupal 6 for searching through CCK. I need the user to search between his nodes (node.uid=x) and of a certain type (type='xyz'). I think I have to implement hook_search but I don't know where to put my filters. Can anyone help me?
You already accepted an answer (which is probably the best option for you), but there are a few other ways to accomplish this.
IIRC, the Custom Search module will work for what you want.
You can copy the stock hook_search function to a custom module and modify the query. You can do something like this:
// ...
case 'search':
// Build matching conditions
list($join1, $where1) = _db_rewrite_sql();
$arguments1 = array();
$conditions1 = 'n.status = 1';
// NEW BIT START
$allowed = array(
'content_type_1',
'content_type_2',
'content_type_3',
);
$types = array();
foreach ($allowed as $t) {
$types[] = "n.type = '%s'";
$arguments1[] = $t;
}
$conditions1 .= ' AND ('. implode(' OR ', $types) .')';
$keys = search_query_insert($keys, 'type');
// NEW BIT END
This replaces the bit that extracts the type from the actual query string.
You would have to add in the bit to restruct to a particular n.uid. I have been using this method lately, rather that Custom Search, because it simpler from the user's perspective.
HTH
You might try creating a Views with an exposed filter, it's the absolute easiest way to implementing your idea.
Also you can try use CCK Facets. But Views - of course simple.

How to use multiple filters to widen the search in Apachesolr queries

Making a search with Apachesolr, i want to add a couple of filters in hook_apachesolr_prepare_query(&$query). This works fine, except I want the filters to widen the search ('OR'), rather than narrow it ('AND').
For example, if I have 4 nodes of type:A and 3 of type:B that match a search, to filter by type:A and type:B should return 7 nodes (of type:A AND nodes of type:B), rather than 0 those of type:A which are also of type:B.
I saw a suggestion to do this using the model of nodeaccess
foreach ($filters as $filter) {
$subquery = apachesolr_drupal_query();
if (!empty($subquery)) {
$subquery->add_filter('type', $filter);
$query->add_subquery($subquery);
}
}
but this doesn't seem to work. (It doesn't return any results).
I then tried (as I have a limited number of node types) excluding the types that I don't want:
$excludes = array('A', 'B', 'C');
$excludes = array_diff($excludes, $filters);
$exclude = implode('&', $excludes);
$query->add_filter('type', $exclude, TRUE);
This method of stitching them together doesn't work (the '&' gets escaped) but neither does adding them as subqueries, similar to the manner above.
Any suggestions on how to do this?
With Drupal7 and the last apacheSolr API, you can do OR filters by doing this :
function my_module_apachesolr_query_alter($query) {
// first, create a subQuery filter to store others
// and specify there is a "OR" condition
$filter = new SolrFilterSubQuery('OR');
// next, add all filters on bundle you want, each as
// a new subQuery filter, always with "OR" condition
// and add it to the primary filter
$a = new SolrFilterSubQuery('OR');
$a->addFilter('bundle', 'A');
$filter->addFilterSubQuery( $a );
$b = new SolrFilterSubQuery('OR');
$b->addFilter('bundle', 'B');
$filter->addFilterSubQuery( $b );
$c = new SolrFilterSubQuery('OR');
$c->addFilter('bundle', 'C');
$filter->addFilterSubQuery( $c );
// finally, add the primary subQuery filter as
// subquery of the current query
$query->addFilterSubQuery( $filter );
}
And your query search about type A OR type B OR type C (all results in each types). You can combine OR / AND by changing the parameter of the SolrFilterSubQuery instanciation.
Special thanks to this page and it's author : http://fr.ench.info/blog/2012/04/03/Add-Filters-ApacheSOLR.html
I havenť played with SOLR much but I am quiete familiar with Drupal and Zend Lucene (or Drupal Lucene API).
I would suggest that you try to filter your results based on content type (because each node has its content type stored in the object).
The second idea is to change basic operator. I am not sure how it is done in SOLR but i Zend Lucene
Zend_Search_Lucene_Search_QueryParser::setDefaultOperator($operator) and Zend_Search_Lucene_Search_QueryParser::getDefaultOperator() methods, respectively.
Docs can be found in Zend Lucene Docs. Or for SOLR Solr Docs.
I hope a got your problem right.
Hope it helps :-)

Drupal: Return SQL string from db_query

Is it possible to return the actual SQL query as a string from the result of db_query?
Or otherwise take the returned resource ID from db_query and get the SQL string?
Edit:
As an addendum, I recently found out about db_queryd() from the Devel module, which echoes the query passed (as well as execute it). Doesn't return the string as this question asked, but really helpful for copying and pasting a complete query.
I don't think it is. However if you are only doing so for the purpose of debugging you can turn on the devel module and that will show you the queries run.
Actually you could just set the variable 'dev_query' to 1 and then access the global array $queries, but I wouldn't recommend it.
Drupal 7, if debug, you could find at \includes\database\database.inc:
function query($query, array $args = array(), $options = array())
$stmt's queryString
or
print_r($stmt->getQueryString());
If you have D7 but don't have Devel to hand, the following snippet could come in useful — it may not handle every type of placeholder however... it currently wrongly assumes all placeholders are strings (which has been fine for my usage).
function stringify_query( $query ){
$s = preg_replace('/\}|\{/', '', $query->__toString());
$a = $query->arguments();
foreach ( $a as $key => $val ) {
$a[$key] = '\'' . $val . '\'';
}
return strtr($s, $a);
}
It also rudely strips out Drupal's curly braces used to handle table prefixes, if you rely on table prefixes then you should find the correct Drupal function to have them replaced correctly.
I would recommend the use of the devel module. There is a setting devel offers which will show all queries run during the generation of a page at the bottom of the page, with data on query execution time and the function that called db_query(). If you have a general idea of what your query will look like or the function that called it, you could search for it within your browser and you can see what was actually send to the database.
Late answer, but you can often turn
$result = db_query($query, $arg1, $arg2);
quickly into
drupal_set_message(sprintf($query, $arg1, $arg2), "status");
And get what you want.
This doesn't help you if you are using an array as your argument to db_query as sprintf doesn't support that, but is often useful in your debugging toolkit.
For those using Drupal 7.x and the Devel module, the correct function to call to output the built SQL statement to the drupal message area is dpq(). It needs to be passed the query object though. e.g.
// to see the built SQL
$query = db_select('node', 'n')->fields('n');
dpq($query);
// to see the results of the query
$results = $query->execute()->fetchAssoc();
dsm($results);
Hope that can help!
D7 version with devel.
>= PHP 5.4
dpm(str_replace(['{', '}'], '', dpq($query, TRUE)));
< PHP 5.4
dpm(str_replace(array('{', '}'), '', dpq($query, TRUE)));

Resources