How I can push data in some tables Joomla ignore errors?

I have an array with data in it.

$data[1] = 1
$data[2] = 2
$data[3] = 3

How I can push this data in ~ five tables of Joomla, which have only part of columns (1,2; 2,3; 3,1 etc)?

The Code I want to get running:

foreach ($tables as $table)
    {
      push $data;
    }

Your Goal:

You want to loop through 5 Joomla tables and insert only part of the $data into each table, depending on which columns the table has.


Sample Working Code:

$data = [
    1 => 1,
    2 => 2,
    3 => 3,
];

// Define table names and required columns for each
$tables = [
    ['name' => '#__table1', 'columns' => [1, 2]],
    ['name' => '#__table2', 'columns' => [2, 3]],
    ['name' => '#__table3', 'columns' => [3, 1]],
    ['name' => '#__table4', 'columns' => [1]],
    ['name' => '#__table5', 'columns' => [2]],
];

// Get the database object
$db = JFactory::getDbo(); // or use \Joomla\CMS\Factory::getDbo(); in Joomla 4+

foreach ($tables as $table) {
    $columns = [];
    $values = [];

    foreach ($table['columns'] as $key) {
        if (isset($data[$key])) {
            $columns[] = 'col' . $key;       // Assuming your DB columns are named col1, col2, etc.
            $values[] = $db->quote($data[$key]);
        }
    }

    $query = $db->getQuery(true)
        ->insert($db->quoteName($table['name']))
        ->columns($db->quoteName($columns))
        ->values(implode(',', $values));

    $db->setQuery($query)->execute();
}

Assumptions:

  • Your database columns are named like col1, col2, col3.
  • You have 5 tables with varying combinations of those columns.
  • This works in Joomla 3 or 4.