0

Trying to do a simple query from a table called 'raffles' under the drupal database.

It is not a complex query, Just trying to get all sets from drupal.raffles

$query = db_select('raffles');
$query->execute();
$result = $query->fetchAssoc();
dpm($result);

The error

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'FROM raffles raffles' at line 1: SELECT FROM {raffles} raffles; Array ( ) in raffle_create_form() (line 8

From the error, the query has the table name twice, and is probably what is causing the error. maybe im doing something wrong? There is not much information related to this on the api page.

Any help would be gladly appreciated.

Thanks.

2

You haven't selected any fields:

$result = db_select('raffles', 'r')
  ->fields('r', array('foo', 'bar'))
  ->execute()
  ->fetchAll();

If you want to select all the fields, then use the following code.

$result = db_select('raffles', 'r')
  ->fields('r')
  ->execute()
  ->fetchAll();

Incidentally, the second raffles is a valid alias and not related to the problem.

  • Thanks a bunch. Quick question - how do i go about retrieving all rows in the table? :) – Haider Ali Jan 18 '16 at 18:11
  • You already are ;) Without any conditions or wheres, there's no filter so the query will just be equivalent to SELECT * FROM raffles – Clive Jan 18 '16 at 18:12
  • i use dpm to dump $result, and all i get is one row of data. There are two rows in the table. Maybe im overlooking something here – Haider Ali Jan 18 '16 at 18:14
  • Switched to fetchAll(); and i get them all now :) – Haider Ali Jan 18 '16 at 18:15
  • 1
    Ah yes I should've noticed that - fetchAssoc is one to loop over (foreach ($result->fetchAssoc() as $record) { ...), there are other shortcuts like fetchAll(), fetchAllAssoc() and so on – Clive Jan 18 '16 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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