-1

I have an array like:

$arrays = array(
array('id' => '1','Name' => 'Monica','online' => '1'),
array('id' => '2','Name' => 'Jessica','online' => '1')
);

I only included 2, but let's say I have 200 of these. I already have a table in SQL with associated columns id, name and online.

Can you help me input these into database? I'm developing using wordpress. From Insert array into MySQL database with PHP I have an idea of how to do it for 1 single array

Community
  • 1
  • 1
GRS
  • 2,807
  • 4
  • 34
  • 72
  • 1
    @neophyte what's with the edit here? http://stackoverflow.com/review/suggested-edits/15294715 it clearly defaces the question with what they looked into and probably tried. – Funk Forty Niner Feb 22 '17 at 01:36

2 Answers2

2

If you're having an array , you need to use a foreach loop to know the length content of insertion.

This is an example of insertion:

if(is_array($array)){

    $sql = "INSERT INTO some_table (id, name, online) values ";

    $valuesArr = array();
    foreach($array as $row){

        $id= (int) $row['id'];
        $email = mysql_real_escape_string( $row['name'] );
        $name = mysql_real_escape_string( $row['online'] );

        $valuesArr[] = "('$id', '$email', '$name')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}
FreedomPride
  • 1,098
  • 1
  • 7
  • 30
1

Please try this.

Using PDO example

$sql = <<<EOT
INSERT IGNORE INTO
       table_name (id, name, online)
   VALUES
       (:id, :name, :online)
;
EOT;
define("INSERT_UPDATE_SQL", $sql,true);


try{

    $con = new PDO(CONNECTION_STRING);

    if(is_array($arrays)){

        $stmt = $con->prepare(INSERT_UPDATE_SQL);
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':online', $online);

        foreach($arrays as $row){
            $id = (int)$row['id'];
            $name = $row['Name'];
            $online = $row['online'];

            $stmt->execute();
        }
        $stmt = null;
    }

    $con = null;
}catch (PDOException $e) {
    echo 'error !!';
    throw $e;
}

not changed if already registered.

taku
  • 11
  • 2