0

I'm trying to learn how to make select queries with Drupal, so I made a form, and when I submit the form I try to query the database and get some results, but instead I'm redirected to an error page, here's how I select nodes from DB :

function my_module_form_submit($form, &$form_state)
{
    $query = db_select('node', 'n')->extend('PagerDefault');
    $query->condition('type', 'myContentType');
    $result = $query->execute();
}
2
  • 1
    What is the error message?
    – sareed
    Jan 9, 2015 at 14:45
  • I'm not getting any error message :/
    – teeyo
    Jan 9, 2015 at 14:50

2 Answers 2

1

You have missed fields() & fetch type -- fetchAll().

Below is the working example. You can find more details here (db_select API)

$query = db_select('node', 'n')->extend('PagerDefault');
$query->fields('n'); // This is like select *. You can retrieve specific fields too.
$query->condition('type', 'article');
$result = $query->execute()->fetchAll(); // you can fetch by object, array, etc...
print_r($result);
1
  • Yup thanks, I used fetchObject with a while loop.
    – teeyo
    Jan 20, 2015 at 10:00
0

I don't know exactly what was the issue with the code I used before, but using a more advanced query resolved the problem ( being redirected to an error page ) :

$query = db_select("node", "n");
$query->fields("n", array("nid"));
$query->fields("n", array("created"));
$query->fields("n", array("type"));

$query->fields("f1", array('field_f1_value'));
$query->fields("f2", array('field_f2_value'));
//...

$query->leftJoin('field_data_f1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_f2', 'f2', 'f2.entity_id = n.nid');
// ...

$query->condition('n.type', 'voitures_d_occasion', '=');
$query = $query->orderBy('n.created', 'DESC');
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(10);
$result = $query->execute();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.