php+mysql: insert a php array into mysql

后端 未结 4 593
时光取名叫无心
时光取名叫无心 2020-12-22 07:54

I have an array with 30000 plus entries that need to go into a MySQL table.

What is the best practice? From here? Lets say [0], [1] and [2] in the database would be

相关标签:
4条回答
  • 2020-12-22 08:17
    $statement = "INSERT INTO table (title, type, customer) VALUES ";
    foreach( $data as $row) {
       $statement .= ' ("' . implode($row, '","') . '")';
    }
    

    UPDATE: Changed explode to implode (I always get those confused).

    0 讨论(0)
  • 2020-12-22 08:18

    Magic function? I'm guessing you mean some sort of DB abstraction layer? IMHO that would just double your work.

    Just build the query manually looping through array[] INSERT'ing values as you go.

    0 讨论(0)
  • 2020-12-22 08:24

    I would say just build it yourself. You can set it up like this:

    $query = "INSERT INTO x (a,b,c) VALUES ";
    foreach ($arr as $item) {
      $query .= "('".$item[0]."','".$item[1]."','".$item[2]."'),";
    }
    $query = rtrim($query,",");//remove the extra comma
    //execute query
    

    Don't forget to escape quotes if it's necessary.

    Also, be careful that there's not too much data being sent at once. You may have to execute it in chunks instead of all at once.

    0 讨论(0)
  • 2020-12-22 08:25

    You will have to build the query manually if you want the best performance during this operation. If you would iteratively add everything using PDO or some abstarction layer, you will have 30000+ insert queries.

    Use foreach to iterate over the arraay, build one nested INSERT query that does all the work at once, and just send it to the server.

    0 讨论(0)
提交回复
热议问题