I suspect this is probably an easy answer, but not nowing what to search for is making it a lot harder to find :)

I have node(1) on which I link to another node(2). I want to have available the "title" of node(2) so I can use it as the title of the link and other purposes

Any guidance would be much appreciated

Comments

3cwebdev’s picture

I suspect the answer would depend on the context of your scenario. Asumming you have the $node object loaded then you could simply use $node->title

If the node object is not loaded, you can use node_load() to load it first.

grobemo’s picture

It sounds like you're trying to do this while theming node1 (where node2, the one you want, references node1). In that case, $node->title will give you the title of node1.

To print a link to node2 using its title as the link text, you'll need to do something like this (assuming that $nid2 is the nid of node2):

<?php
$node2 = node_load($nid2);
print '<a href="/node/'. $nid2 .'">'. $node2->title .'</a>';
?>

(Ideally, the first line should be done in a template.php file in your theme folder and used to set variables like $node2_nid and $node2_title, which would then be used in your node-type.tpl.php template file. But if that all sounds like gibberish to you, then the above code will do for now.)

Uh...in other words, what setfree said. I wrote this before noticing the last line of setfree's comment where node_load was already suggested....

cog.rusty’s picture

I assume you have enabed the "php filter" module.

While editing node 1, set its input format to "php code". Assuming the nid of node 2 is 2:

$node = node_load(2);
print l($node->title, 'node/2');

But you can't let anyone else do this (using the "php code" input format), because they can take away your admin account, change passwords, or edit anything they want.

Anonymous’s picture

Many thanks to you all for your replies. The basic scenario was that I was adding some code to a "Contemplate". Although I was aware you could do $node->title to get the title for the current node, I had no idea that you could get it for another node.

I had just resolved the issue when i saw all the replies :) However I much prefer the methods shown here, and have now implimented them as a replacement.

If your curious as to how I did get the data, it was using the following

$sql = "SELECT title FROM {node} WHERE nid =$mynode"; 
$result = db_query($sql);
$link_title = db_result($result); 

Again many thanks for your replies,

grobemo’s picture

It may not be much of an issue, depending on how you're getting $mynode, but your SQL query has a small security hole in it. It's probably better to use:

$sql = 'SELECT title FROM {node} WHERE nid = %d';
$result = db_query($sql,$mynode);
$link_title = db_result($result);

Drupal will then make sure that $mynode can't be used for an SQL injection attack. See the section on "Capitalizaion and user-supplied data" in the Drupal SQL coding conventions.

Anonymous’s picture

Many thanks for that. Its good to learn how to make things better.

Although I won't be using it this time, as the other method is far better, I had saved the code for a later day, but now I and hopefully others who see this thread, will be able to do it right :)

ferrangil’s picture

Which is better to just get the node title? In terms of performance I mean... that simple SQL is much faster than doing the whole node_load, right? I think it also deppens on how big is the node you are trying to load.
I'm doing it just now, to get the title (name) of a person node, which only has 2 text fields (name and lastname) and the title is just the combination.
It looks like the node_load is the drupal way to do that, but...
Suggestions?

cog.rusty’s picture

Doing it with a single well-written SQL query is usually faster. How much faster, milliseconds of tenths of a second, depends on the query. Of course a badly written query can be slower.

Using Drupal's API functions generally makes it easier to write code, may cover different SQL environments and special cases, and keeps the code working even if the database schema changes (at least as long an the API itself doesn't change).

That query was rather trivial to write, but I believe it is better to trade a fraction of a second for sticking with a good habit.

ferrangil’s picture

Yep, I will go with the node_load way, as I might need to get some other value from that node in a future, and it will be easier to print $node->another_field than rewriting the query.
It all depens on how many items are listed on the page, as if the value is too high, maybe the delay for using node_load is more appreciable.
Thanks!

Gabriel R.’s picture

How about getting the node title without loading the node?

I'd like to do it like this...

print l(get_title_magically(72),"node/72";

Thanks.

cog.rusty’s picture

Easy. You write a function get_title_magically($nid).

function get_title_magically($nid)
{
 $node = node_load(array('nid'=>$nid));
 return $node->title;
}

and then you use it exactly as you did.

ferrangil’s picture

That function loads the node, so it's just a shorter method but it does the same. I think he asked for this functionality without doing a node_load (for performance maybe...).

cog.rusty’s picture

If you want a specified node I don't think you can avoid loading it. They are not all in memory.

If you want the current displayed node, again you need to construct the node object. It is the way to access the node's information, and there is some caching going on, so (I think) it won't run a query.

An exception where the current displayed node's object is already loaded is the theme's node.tpl.php file and page.tpl.php file (when you are on a full node page), and that works only for the current node (not when specifying another node).

grobemo’s picture

If you really want to load the title without loading the node, you could do this:

<?php

function get_title_magically($nid) {
  return db_result(db_query('SELECT title FROM {node} WHERE nid = %d',$nid));
}

?>

As cog.rusty pointed out above, though, the minimally reduced load time probably isn't worth sacrificing the cleaner coding standards. Also, if you're going to do this for many nodes on every page, it's probably worth pulling all the titles with a single SQL command, storing them in an associative array, and printing them from there.

Some variations:

<?php

// Slightly more secure, since it sanitizes the title; not necessary if you're using l().
function get_title_magically($nid) {
  return check_plain(db_result(db_query('SELECT title FROM {node} WHERE nid = %d',$nid)));
}

// Get titles for published nodes only.
function get_title_magically($nid) {
  return db_result(db_query('SELECT title FROM {node} WHERE nid = %d AND status = 1',$nid));
}

?>
kevinqin’s picture

thanks for the post

crunk’s picture

I'm still kinda new to drupal. I'll give you an example code that isn't working. It seems I can't pull info out of a node that I get from node_load.

<?php foreach((array)$node->field_related_services as $item) {?>
  <div class="field-item">
    <?php $ref_node = node_load($item['nid']); ?>
    <h3><? print $ref_node['title']?></h3>

The code of course doesn't end there, but to be simple I'm only including the code that is messing up. My code breaks as soon as it hits $ref_node['title']. Any suggestions or answers to that?

3cwebdev’s picture

Are you sure that $item['nid'] contains a node ID number?

To print the title, try:

<?php print $ref_node->title; ?>
crunk’s picture

Thanks so much, the $ref_node->title works! Silly mistake, all part of the learning process I assume...

rj’s picture

Crunk, you may want to post this as a new issue, the issue you replied to is old. I noticed, however, that you are missing some php brackets:

<? print $ref_node['title']?>

Should be:

print $ref_node['title']

If you have devel installed, you can use dprint_r($ref_node); to get a pretty clean printout of arrays.

--rj

wiliam_steven’s picture

Hi, all

I have looking a solution to print node title, from every articles that I have searching, I have found to using

print $node->title;

but i have using devel to Execute PHP code, it not printing anything. Any suggestion ?

thank you before.

nevets’s picture

Where are you putting the print statement?

couloir007’s picture

I needed to print the body summary in view header, D7, and wrote this code snippet and added it my custom module.

print my_function_node_load_field(19034, 'body', 'summary');

function my_function_node_load_field($nid, $field, $value = 'value') {
	$fld = $field . '_' . $value;
	$tbl = 'field_data_' . $field;

	$result = db_query("SELECT {$fld} FROM {$tbl} WHERE entity_id = :nid",	array(':nid' => $nid));

	foreach ($result as $rec) {
		return $rec->{$fld};
	}
}
ajitdalal’s picture

$node_title = db_query("SELECT title FROM {node} WHERE nid = :nid", array(
        'nid' => $nid,
     ))->fetchCol();