开发者

How to insert data from multiple array to database PHP?

How to insert data from multiple array to database PHP&MYSQL?

I have created one table name is student. There are 3 fields ID,Name and Sex.

Example: Array ( [0] => 1,Jam,M [1] => 2,Janny,F [2] => 3,Vary ).

Table students there 3 fields ID,NAME,SEX.

How to insert multiple ar开发者_如何学Cray into Table students?


Think of it not in terms of database inserts but in terms of strings.
PHP is a string manipulation language.
All you need is to compose a string of some format. So, first of all you have to write down an example of desired string, an INSERT SQL query.
And then use PHP to assembly such a string using some PHP code.


$arr = Array ("1,Jam,M","2,Janny,F" ,"3,Vary,M" );

$VALUES = array();
foreach ($arr as $data)
  $VALUES[] = '('.implode(',',array_map("escape", explode(',', $data))).')';  

$query = 'INSERT INTO STUDENTS_TABLE (`id`, `name`, `sex`) VALUES '.implode(',', $VALUES);
mysql_query($query, $db_con);

function escape($str)
{
  //escaping  here . For example
  global $db_con; 
  return '"'.mysql_real_escape_string($str, $db_con).'"';
}

This is only example but I suggest you to use multi inserting.


You should try doing a foreach loop, like this:

<?php
$arr = Array ( [0] => "1,Jam,M" [1] => "2,Janny,F" [2] => "3,Vary" );
foreach($arr AS $item)
{
    $parts = explode(",", $item);
    $q = sprintf("INSERT INTO students (id, name, sex) VALUES ('%s', '%s', '%s')", $parts[0], $parts[1], $parts[2]);
    // now execute the query into your database - like
    mysql_query($q);
}

I noticed your third element does not contain sex, so you should check for validity in case it's needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜