Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Drupal 7 database API

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 146
    Comment on it

    Drupal database abstraction layer allow's the use of different database servers using the same code base i.e it provides with the ability to support multiple database servers easily. The system is built a top PHP's PHP Data Objects database API and inherits much of its syntax.

    with select query we can use:

        execute($arg=array(), $option = array())
        fetchAllAssoc($key, fetch=null)
        fetchAllKeyed($keyindex=0, $valueindex=1)
        fetchAssoc()
        fetchCol($inde=0)
        fetchField($inde=0)
        getQueryString()
        rowCount()
    

    Some very basic example are as under:

    Basis SQL Select query:

        Select n.name, n.decription, created FROM node n WHERE n.uid = $uid
          ORDER BY n.created DESC LIMIT 0, 5; 
    

    Select in Drupal 7 way :

    <?php 
    
        $query = db_select('node', 'n');
        $query->fields('n', array('name', 'n.description','created'));
        $query->condition('n.uid', $uid, '=');
        $result = $query->execute();
    
        //count the result
        $datacount = $result->rowCount();
    
        if($datacount > 0){
            //Fetch the data as object from database
            $data = $result->fetchAll();
        }
    ?>
    

    Basis SQL Insert query:

        insert into mytable(intvar1, intvar2, floatvar, strinvar) values (10, 90, 67.9, 'myapp');
    

    Insert in Drupal 7 way :

    <?php
        $nid = db_insert('mytable')
        ->fields(array(
        'intvar1', => 10,
        'intvar2' => 90,
        'stringvar' => 'myapp',
        'floatvar' => 3.14
        ))->execute();
        ?>
    

    Basis SQL Update query:

    update myapp SET stringvar = 'yourapp' where intvar1 = 10;
    

    Update in Drupal 7 way :

    <?php 
    
        $nidupdate = db_update('mytable')
         ->fields(array(
            'stringvar' => 'yourapp'
        ))
        ->condition('invar1', 10 ,'=')
        ->execute();
        ?>
    

    Basis SQL Delete query:

     Delete from myapp where intvar1 = 10;

    Drupal 7 Way :

    <?php
    delete('myapp')->condition('invar1', 5, '=')->execute();
    ?>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: