如何在数据库中插入多个数组行?

时间:2013-07-14 17:10:36

标签: php html phpmyadmin

我正在研究动态数组我需要在数据库中插入这些数组。当我将动态数组插入数据库而不是插入所有行时,它只在数据库中插入一行。

下面的

是包含结果的数组

$asma[]=GA::select($ga->population,'total',3);

下面是在数据库表ga

中插入多个数组的代码
<?php 
//code not tested check it

//Logic is changed instead of for looping many times
$data = array();

$j = 0;

foreach($asma as $key => $value)
{
$i = 0;

foreach ( $value as $ind => $hObject )
{
    if($i==0)
    {
        $data[$j]['fe'] = mysql_escape_string($hObject->Voltage);

    }else{

        $data[$j]['fe'.$i] = mysql_escape_string($hObject->Voltage);
    }

    $i++;

    $data[$j]['fe'.$i] = mysql_escape_string($hObject->Duration);
    $i++;

    $data[$j]['fe'.$i] = mysql_escape_string($hObject->Number);
    $i++;

}

$j++;

}// endforeach

//multiple array
 foreach($data as $array)
 {


 //unique array
//$array3 = array_merge($Voltage,$Duration,$Number);

$fields = implode(',',array_keys($array));

//if you want append any new field append it
$fields .= ','.'timestamp,username';

$vals = "'".implode("','",array_values($array))."'";

//if you want append any new values append it
$vals .= ",'".time()."','".$login_session."'";


$q = "INSERT INTO ga (".$fields.") VALUES(".$vals.")";

$result = mysql_query($q);
if ( ! $result ) {
    die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
 }

每当用户输入3然后计算结果将存储在数组asma之后,存储结果将存储在表ga中,该表应该是三行但在表中只插入一行并显示而不是三如果用户在文本框中输入任何值,则相同。

1 个答案:

答案 0 :(得分:0)

我不确定你的意思,我认为这是一个插入语句:

INSERT INTO `ga` (`field1`, `field2`, `field3`, `etc`)
VALUES (value11, value21, value31, more_values1),
    (value12, value22, value32, more_values2),
    (value13, value23, value33, more_values3)

因此,您应该使用foreach周期来创建值语句。

$sql = "INSERT INTO `ga` (`voltage`, `duration`, `number`, `timestamp`, `username`) VALUES ";

$values = "";
foreach ($asma as $row) {
    $values .= ($values != "" ? "," : "") . "(" .
            "'" . $row['voltage'] . "', " .
            "'" . $row['voltage'] . "', " .
            "'" . $row['number'] . "', " .
            "'" . time() . "', " .
            "'" . $login_session . "'" .
            "),";
}

$sql .= substr($values, 0, -1) . ";";