Friday, May 2, 2014

Auto sync two mysql tables with exception

Auto sync two mysql tables with exception

-- this is comment in SQL language (line starts with --)
CREATE EVENT event_daily_copy_something
    ON SCHEDULE
      EVERY 1 DAY
    COMMENT 'This text will appear in MySQL Workbench as description of event'
    DO
      BEGIN
        INSERT INTO your_db_name.target_table_name(id, field)
          SELECT id, something
            FROM your_db_name.source_table_name
            WHERE id = 3;
      END

Synchronization of tables is quite complicated. I think you need few operations in event.
  1. Check for new rows and copy
  2. Check for deleted rows and delete them in "copy" table
  3. Check for changed rows (here trigger on source table would be very useful, because trigger "knows" what row is edited and you can access new field values in table 1 and use them to update table 2).

Thursday, May 1, 2014

How to insert 3 or multiple arrays into 1 or 2 MySql tables

After googling for 2 days, Here is how to add multi-arrays into MySQL tables

Example we have 3 arrays:

$item= array(1, 2, 3, 4, 5);
$fruit= array('apple', 'banana', 'ananas', 'orange', 'lemon');
$price= array(32, 54, 26, 97, 47);

foreach($fruit as $key => $fruitName)
    {
    $query = " INSERT INTO fruits (item, fruit)
               VALUES ('$item[$key]', '$fruit[$key]')";
    mysql_query($query) or exit(mysql_error());
    $query = " INSERT INTO prices (item, price)
               VALUES ('$item[$key]', '$price[$key]')";
    mysql_query($query) or exit(mysql_error());
    }
This code is working as charm ! Enjoy.