Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to insert, Update & remove data using JDatabase

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 688
    Comment on it

    Inserting data using JDatabase:

    JDatabaseQuery class includes methods such as insert(), columns() and values() to insert data.

    For example:

    // Get a db connection.
    $db = JFactory::getDbo();
    
    // Create a new query object.
    $query = $db->getQuery(true);
    
    // Insert columns.
    $columns = array('columnn_name_1','column_name_2',......,'column_name_n);
    
    // Insert values.
    $values = array($db->quote(value_1),$db->quote('value_2'),.......,value_n); // if value is string then use quote() method to insert else insert it normally without any quote
    
    // Prepare the insert query.
    $query
        ->insert($db->quoteName('#__table_name')) //write your table name in place of table_name
        ->columns($db->quoteName($columns))
        ->values(implode(',', $values));
    
    // Set the query using our newly populated query object and execute it.
    $db->setQuery($query);
    $db->execute();
    
    

    Updating data using JDatabase:

    To update data in database using JDatabaseQuery class two methods are used update() and set().

    For example,

    // Get a db connection.
    $db = JFactory::getDbo();
    
    // Create a new query object.
    $query = $db->getQuery(true);
    
    // Fields to update.
    $fields = array(
        $db->quoteName('field_name_1') . ' = ' . $db->quote('value1'),
    $db->quoteName('field_name_2') . ' = value_2'
    );
    
    // Conditions for which records should be updated.
    $conditions = array(
        $db->quoteName('field_name') . ' = value'
    );
    
    $query->update($db->quoteName('#__tablename'))->set($fields)->where($conditions);
    
    $db->setQuery($query);
    
    $result = $db->execute();
    
    

    Deleting a record using JDatabase:

    Here, delete() method is used to delete the record based on some conditions.

    Example:

    $db = JFactory::getDbo();
    
    $query = $db->getQuery(true);
    
    // delete record based on value
    $conditions = array(
        $db->quoteName('field_name') . ' = value', 
    
    );
    
    $query->delete($db->quoteName('#__table_name'));
    $query->where($conditions);
    
    $db->setQuery($query);
    
    $result = $db->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: