How do I print a single comment in drupal? - php

I want to print a individual comment in drupal based on it's comment ID. How can I do this? Google and other sources have yielded me nothing. Thank you.

Eaton's suggestion is good (except it's {comments}, not {comment}) if you need to display the comment like core does it, including the info coming from the node. Except the default theme_comment implementation in modules/comment/comment.tpl.php makes no use of $node.
However, I'd do it slightly differently, because if you need to extract a single comment, displaying it with the normal content formatting provided by comment.tpl.php is likely to be inappropriate.
function print_comment($cid) {
$sql = "SELECT * FROM {comment} c WHERE c.cid = %d";
if ($comment = db_fetch_object(db_rewrite_sql(db_query($sql, $cid), 'c'))) {
return theme('my_special_comment_formatting', $comment);
}
}
And of course, define this special commment formatting in your module's hook_theme() implementation, inspired by what comment.tpl.php does.
2014-02 UPDATE: note that this is a 2009 question/answer. In Drupal 8, you just don't want to access the hypothetical underlying SQL database (and would not do it like this anyway, but use DBTNG), but just use something like:
if ($comment = entity_load('comment', $cid)) {
return entity_view($comment, $view_mode);
}

function print_comment($cid) {
$sql = "SELECT * FROM {comments} WHERE cid = %d";
if ($comment = db_fetch_object(db_query($sql, $cid))) {
$node = node_load($comment->nid);
return theme('comment', $comment, $node);
}
}

No reason to use any sql to do this, two drupal api function calls is all it takes.
function print_comment($cid)
{
$comment = _comment_load($cid);
return theme('comment',$comment);
}

Related

Create a reddit-like infinite levels comment reply system [duplicate]

This question already has answers here:
Generating Depth based tree from Hierarchical Data in MySQL (no CTEs)
(4 answers)
Closed 7 years ago.
Imagine an comment system with an infinite reply structure. Like this:
Comment
Reply to comment
Reply to reply to comment
Reply to reply to reply to comment
etc....
Reply to comment
Comment
Reply to comment
Like reddit has:
I am trying to think of a structure inside PHP combined with mysql to do this. I thought of something like this:
$query = mysqli_query($link, "SELECT * FROM comments");
while($comment_array = mysqli_fetch_assoc($query)){
echo $comment_array['text'];
$query_reply = mysqli_query($link, "SELECT * FROM comments WHERE reply_id='$comment_array[id]'");
while($reply_array = mysqli_fetch_assoc($query_reply)){
echo $reply_array['text'];
$query_reply2 = mysqli_query($link, "SELECT * FROM comments WHERE reply_id='$reply_array[id]'");
while($reply_array2 = mysqli_fetch_assoc($query_reply2)){
echo $reply_array['text'];
...... etc.
}
}
}
But as you can see there is a problem in this structure. This structure is not infinite and the same bit of code must be repeated a lot of times.
Is there a way to do this more efficiently? Putting a loop somewhere? Making a function, like searchRepliesofComment();?
There are a few ways to handle this without unbound recursion. A recursive function calling the DB repeatedly is not a good idea, even for reads. A few calls in a test environment may only take a few milliseconds each but even a little traffic can bring the DB to its knees when each request is firing off tons of DB hits.
First option you could have a post_id,parent_reply_id on all replies. The post_id would allow to select all replies that apply to a post but would have no hierarchy. Then you would build the reply tree in memory using parent_reply_id. Replies with a null parent_reply_id would represent top level replies. You could build this map easily with "SELECT * FROM replies WHERE post_id = ? ORDER BY parent_reply_id ASC". Ordering this way will make building the tree really straight forward.
You can also use the nested set model. Here is a great example. It does incur the cost of having to do a bulk (but relatively) light write operation on many replies when a new reply is added but the benefit is that you can build the tree with a single mysql query.
You will want to build what's known as a recursive function
function getComments($link, $parent = null)
{
$sql = "SELECT * FROM comments";
$sql .= $parent ? " WHERE reply_id=".(int)$parent : null;
$query = mysqli_query($link, $sql);
$results = array();
while ($result = mysqli_fetch_assoc($query)) {
if ($children = getComments($result['id'])) {
$result['children'] = $children;
}
$results[] = $result;
}
return $results;
}
function renderComments(array $comments)
{
$output = '';
foreach ($comments as $comment) {
$output .= $comment['text'];
if (isset($comment['children'])) {
$output .= renderComments($comment['children']);
}
}
return $output;
}
Now you can render your comments like:
renderComments(getComments($link));

Pulling settings from MySQL using Object-Orientated PHP

Ok, so I am slowly migrating from Procedural to OOP, and I'm finding it all pretty straight forward apart from one thing.
I used to use this method for pulling my settings data from a simple two-column settings table comprising of a row for each setting, defined with 'setting' and 'value' fields:
$query = mysql_query("SELECT * FROM `settings`");
while ($current_setting = mysql_fetch_array($query)) {
$setting[$current_setting['setting']] = $current_setting['value'];
}
As you can see, I manipulated it so that I could simply use $setting['any_setting_name'] to display the corresponding 'value' within that setting's row. I'm not sure if this is a silly way of doing things but no matter, I'm moving on anyway..
However, since moving to object orientated PHP, I don't really know how to do something similar..
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
echo $current_setting->setting; // echo's each setting name
echo $current_setting->value; // echo's each setting value
}
As you can see, I'm perfectly able to retrieve the data, but what I want is to be able to use it later on in the form of: $setting->setting_name; which will echo the VALUE from the row where setting is equal to 'setting_name'..
So basically if I have a row in my settings table where setting is 'site_url' and value is 'http://example.com/', I want $setting->site_url; to contain 'http://example.com/'.. Or something to the same effect..
Can anyone help me out here? I'm at a brick-wall right now.. Probably something really stupid I'm overlooking..
Since you are working with a resource it has a pointer. Once you get to the end you can't use it anymore. I think you can reset it but why not mix the new with the old?
I don't think you're going to have too much overhead, any that matters anyway, to do something like this:
$settings = array();
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
$settings[$current_setting->setting] = $current_setting->value;
}
Now you can use $settings as much as you want.
UPDATE
Haven't tested this or used it but are you looking to do something like this? Consider the following pseudo code and may not actually work.
$settings = new stdClass();
$query = $mysqli->query("SELECT * FROM `settings`");
while ($current_setting = $query->fetch_object()) {
$settings->{$current_setting->setting} = $current_setting->value;
}

echo full joomla query (with limit etc)?

I was wondering if there was a way to echo out the full query with limit and limitstart etc. I can echo out the line $query, but i want to see why the limit isn't working and I can't seem to get it to display the actual query that it's sending to the database.. Here's the code:
$params =& JComponentHelper::getParams('com_news');
$limit = $params->get('x_items', 5);
$limitstart = JRequest::getVar('limitstart', 0);
$query = "SELECT * FROM #__news WHERE published = 1 AND catid = ".$Itemid." ORDER BY date DESC";
$db->setQuery($query, $limitstart, $limit);
$rows = $db->loadObjectList();
$db->getQuery($query, $limitstart, $limit); is only displaying "SELECT * FROM jos_news WHERE published = 1 AND catid = 8 ORDER BY date DESC" which doesnt have the LIMIT params on the end of the query..
Any help would be appreciated :)
The JDatabaseQuery object has a __toString() function that outputs the query so you can do:
echo $db->getQuery();
Or if you want to pass it to a function you can explicitly cast it to a string first:
var_dump((string)$db->getQuery());
var_dump($db);die;
Do that after the loadObjectList() call. Inside the $db variable there must be a _sql attribute that is the last query executed.
Agreed with the previous answers, but... In case you are developing your own components, since I often want to know for sure what exactly is executed too, here's a simple solution:
In your models put:
$db = JFactory::getDBO();
echo $db->getQuery();
Where you want to know the query... Don't put it in (for example) your view, since it might have loaded some other dropdown list by way of execution in the meantime...
For example:
For a list-view put it right before the foreach ($items... in the public function getItems() of the model.
In a form-/item-view put it right before the return $data / return $item in the protected function loadFormData() / public function getItem($pk = null)
Hope this helps...
On new joomla versions, you need to echo __toString() on query object.
echo $query->__toString();
I get this info on this joomla answer.
Hope this helps
Joomla provides $query->dump(). To add convenience, I like to wrap it in enqueueMessage() so that the presented string is at the top of the webpage.
JFactory::getApplication()->enqueueMessage(
$query->dump(),
'notice'
);
IMPORTANT: You should never show the raw SQL string or a raw query error string to the public.
See some of my implementations at Joomla Stack Exchange.

Error on specific search query

I have a website ongrounds.com there is a search bar on top when ever I search for word "best" it generates following error
Warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s) AS relevance FROM hotaru_posts WHERE (post_status = %s OR post_status = %s)' at line 1 in /home2/onground/public_html/libs/extensions/ezSQL/mysql/ez_sql_mysql.php on line 264
Notice: Trying to get property of non-object in /home2/onground/public_html/content/plugins/bookmarking/libs/BookmarkingFunctions.php on line 132
But when I search any other word except "best" the search plugin works fine and it shows results. I do not know why it is showing error on word "best". Please help.
SEARCH PLUGIN CODE:
class Search
{
/**
* Add permissions and register search widget
*/
public function install_plugin($h)
{
// Permissions
$site_perms = $h->getDefaultPermissions('all');
if (!isset($site_perms['can_search'])) {
$perms['options']['can_search'] = array('yes', 'no');
$perms['can_search']['default'] = 'yes';
$h->updateDefaultPermissions($perms);
}
// widget
$h->addWidget('search', 'search', ''); // plugin name, function name, optional arguments
}
/**
* Get search results
*/
public function theme_index_top($h)
{
// Get page title
if ($h->cage->get->keyExists('search')) {
$title = stripslashes(htmlentities($h->cage->get->sanitizeTags('search'),ENT_QUOTES,'UTF-8'));
$h->pageTitle = make_name($title);
$h->subPage = 'search';
$h->pageType = 'list';
$h->pageName = 'search';
}
}
/**
* Displays "Search!" wherever the plugin hook is.
*/
public function search_box($h)
{
$h->displayTemplate('search_box', 'search');
}
/**
* Displays "Search!" wherever the plugin hook is.
*/
public function widget_search($h)
{
$h->displayTemplate('search_box', 'search');
}
/**
* Use the search terms to build a filter
*/
public function bookmarking_functions_preparelist($h, $vars)
{
if ($h->cage->get->keyExists('search'))
{
$return = $vars['return']; // are we getting the count or the result set?
$orig_search_terms = stripslashes($h->cage->get->sanitizeTags('search'));
$search_terms = $orig_search_terms;
if ($search_terms)
{
// fetch select, orderby and filter...
$prepared_search = $this->prepareSearchFilter($h, $search_terms, $return);
extract($prepared_search);
$h->vars['orig_search'] = $orig_search_terms; // use this to re-fill the search box after a search
$h->vars['orig_search_terms'] = $orig_search_terms; // used in the breadcrumbs function
return true;
}
}
return false;
}
/**
* Prepare search filter
*/
public function prepareSearchFilter($h, $search, $return = 'posts')
{
$search_terms = strtolower($search);
$search_terms = explode(" ", $search_terms);
$search_terms = array_iunique($search_terms);
$search_terms_clean = '';
$full_text = true; // Do a full text (better) search if all terms are longer than 3 characters
foreach($search_terms as $search_term) {
if ($this->isStopword($search_term)) {
continue; // don't include this in $search_terms_clean
}
if (strlen(trim($search_term)) < 4) {
$full_text = false;
}
$search_term = trim($h->db->escape($search_term));
// if the urlencoded term contains a percent sign, we can't use a full text search
if (strpos(urlencode($search_term), '%') !== false) {
$full_text = false;
}
$search_terms_clean .= $search_term . " ";
}
// Undo the filter that limits results to either 'top', 'new' or archived (See submit.php -> sub_prepare_list())
if (isset($h->vars['filter']['post_status = %s'])) { unset($h->vars['filter']['post_status = %s']); }
if (isset($h->vars['filter']['post_archived = %s'])) { unset($h->vars['filter']['post_archived = %s']); }
// filter to top or new stories only:
$h->vars['filter']['(post_status = %s OR post_status = %s)'] = array('top', 'new');
$select = ($return == 'count') ? "count(*) AS number " : "*";
if ($full_text) {
$h->vars['select'] = array($select . ", MATCH(post_title, post_domain, post_url, post_content, post_tags) AGAINST (%s) AS relevance" => trim($search_terms_clean));
$h->vars['orderby'] = "relevance DESC";
$h->vars['filter']["MATCH (post_title, post_domain, post_url, post_content, post_tags) AGAINST (%s IN BOOLEAN MODE)"] = trim($search_terms_clean);
} else {
$h->vars['select'] = $select;
$h->vars['orderby'] = "post_date DESC";
$h->vars['filter_vars'] = array();
$where = $this->explodeSearch($h, 'post_title', $search_terms_clean) . " OR ";
$where .= $this->explodeSearch($h, 'post_url', $search_terms_clean) . " OR ";
$where .= $this->explodeSearch($h, 'post_content', $search_terms_clean);
$where = '(' . $where . ')';
$h->vars['filter'][$where] = $h->vars['filter_vars'];
}
$prepared_search = array('select' => $h->vars['select'], 'orderby' => $h->vars['orderby'], 'filter' => $h->vars['filter']);
return $prepared_search;
}
/** Explode search for short words
*
* #param string $column
* #param string $search_terms
* #return string (with " OR " stripped off the end)
*/
public function explodeSearch($h, $column, $search_terms)
{
$query = '';
foreach(explode(' ', trim($search_terms)) as $word){
if ($word) {
$query .= $column . " LIKE %s OR ";
$search_term = urlencode(" " . trim($h->db->escape($word)) . " ");
// escape all percent signs for use in LIKE query:
$search_term = str_replace('%', '\%', $search_term);
array_push($h->vars['filter_vars'], "%" . $search_term . "%");
}
}
return substr($query, 0, -4);
}
/**
* Is it a stopword?
*
*#return bool
*/
public function isStopword($word)
{
$word_array = array();
// list came from http://meta.wikimedia.org/wiki/MySQL_4.0.20_stop_word_list
$stopwordlist = "things ii iii a able about above according accordingly across actually after afterwards again against ain't all allow allows almost alone along already also although always am among amongst an and another any anybody anyhow anyone anything anyway anyways anywhere apart appear appreciate appropriate are aren't around as aside ask asking associated at available away awfully be became because become becomes becoming been before beforehand behind being believe below beside besides best better between beyond both brief but by c'mon c's came can can't cannot cant cause causes certain certainly changes clearly co com come comes concerning consequently consider considering contain containing contains corresponding could couldn't course currently definitely described despite did didn't different do does doesn't doing don't done down downwards during each edu eg eight either else elsewhere enough entirely especially et etc even ever every everybody everyone everything everywhere ex exactly example except far few fifth first five followed following follows for former formerly forth four from further furthermore get gets getting given gives go goes going gone got gotten greetings had hadn't happens hardly has hasn't have haven't having he he's help hence her here here's hereafter hereby herein hereupon hers herself hi him himself his hither hopefully how howbeit however i'd i'll i'm i've ie if ignored immediate in inasmuch inc indeed indicate indicated indicates inner insofar instead into inward is isn't it it'd it'll it's its itself just keep keeps kept know knows known last lately later latter latterly least less lest let let's like liked likely little look looking looks ltd mainly many may maybe me mean meanwhile merely might more moreover most mostly much must my myself name namely nd near nearly necessary need needs neither never nevertheless new next nine no nobody non none noone nor normally not nothing novel now nowhere obviously of off often oh ok okay old on once one ones only onto or other others otherwise ought our ours ourselves out outside over overall own part particular particularly per perhaps placed please plus possible presumably probably provides que quite qv rather rd re really reasonably regarding regardless regards relatively respectively right said same saw say saying says second secondly see seeing seem seemed seeming seems seen self selves sensible sent serious seriously seven several shall she should shouldn't since six so some somebody somehow someone something sometime sometimes somewhat somewhere soon sorry specified specify specifying still sub such sup sure t's take taken tell tends th than thank thanks thanx that that's thats the their theirs them themselves then thence there there's thereafter thereby therefore therein theres thereupon these they they'd they'll they're they've think third this thorough thoroughly those though three through throughout thru thus to together too took toward towards tried tries truly try trying twice two un under unfortunately unless unlikely until unto up upon us use used useful uses using usually value various very via viz vs want wants was wasn't way we we'd we'll we're we've welcome well went were weren't what what's whatever when whence whenever where where's whereafter whereas whereby wherein whereupon wherever whether which while whither who who's whoever whole whom whose why will willing wish with within without won't wonder would would wouldn't yes yet you you'd you'll you're you've your yours yourself yourselves zero";
$word_array = explode(' ', $stopwordlist);
if (array_search($word, $word_array) == true) {
return true;
} else {
return false;
}
}
/**
* Add RSS link to breadcrumbs
*/
public function breadcrumbs($h)
{
if ($h->subPage != 'search') { return false; }
$crumbs = "<a href='" . $h->url(array('search'=>urlencode($h->vars['orig_search_terms']))) . "'>\n";
$crumbs .= $h->vars['orig_search_terms'] . "</a>\n ";
return $crumbs . $h->rssBreadcrumbsLink('', array('search'=>urlencode($h->vars['orig_search_terms'])));
}
/**
* If a search feed, set it up
*/
public function post_rss_feed($h)
{
Thank you
It looks like this error will occur if the searched word ist a Fulltext-stopword.
I cant tell you why this results in an error, but maybe this knowledge leads you into successfull investigations.

Can I get feedback on this PHP function that tests if a user has signed up?

I'm just getting started on writing functions instead of writing everything inline. Is this how a reusable function is typically written?
function test_user($user) {
$conn = get_db_conn();
$res = mysql_query("SELECT * FROM users WHERE uid = $user");
$row = mysql_fetch_assoc($res);
if (count($row) == 1) {
return true;
}
else {
return false;
}
}
When someone logs in, I have their UID. I want to see if that's in the DB already. It's basic logic will be used in a
"If exists, display preferences, if !exists, display signup box" sort of flow. Obviously it's dependent on how it's used in the rest of the code, but will this work as advertised and have I fallen for any pitfalls? Thanks!
Try this:
$conn = get_db_conn(); # should reuse a connection if it exists
# Have MySQL count the rows, instead of fetching a list (also prevent injection)
$res = mysql_query(sprintf("SELECT COUNT(*) FROM users WHERE uid=%d", $user));
# if the query fails
if (!$res) return false;
# explode the result
list($count) = mysql_fetch_row($res);
return ($count === '1');
Thoughts:
You'll want better handling of a failed query, since return false means the user doesn't already exist.
Use the database to count, it'll be faster.
I'm assuming uid is an integer in the sprintf statement. This is now safe for user input.
If you have an if statement that looks like if (something) { true } else { false } you should collapse it to just return something.
HTH
That is reuseable, yes. You may want to consider moving the SQL out of the PHP code itself.
Although you weren't asking for optimization necessarily, you might want to consider querying for the user's display preferences (which I assume are stored in the DB) and if it comes back empty, display the signup box. You'll save a trip to the database and depending on your traffic, that could be huge. If you decide to keep this implementation, I would suggest only selecting one column from the database in your SELECT. As long as you don't care about the data, there's no reason to fetch every single column.
First off, you need to call
$user = mysql_real_escape_string($user);
because there's an sql injection bug in your code, see the manual. Second, you can simplify your logic by changing your query to:
SELECT COUNT(1) FROM user WHERE uid = $user;
which just lets you evaluate a single return value from $row. Last thing, once you have the basics of php down, consider looking at a php framework. They can cause you trouble and won't make you write good code, but they likely will save you a lot of work.
Indent!
Overall it looks not bad...check the comments..
function test_user($user)
{
$conn = get_db_conn(); //this should be done only once. Maybe somewhere else...?
$res = mysql_query("SELECT uid FROM users WHERE uid = $user");
$row = mysql_fetch_assoc($res);
//I can't remember...can you return count($row) and have that forced to boolean ala C? It would reduce lines of code and make it easier to read.
if (count($row) == 1) {
return true;
}
else {
return false;
}
}
Also,
if (condition) {
return true;
}
else {
return false;
}
can be rewritten as:
return condition;
which saves quite a bit of typing and reading :)

Categories