0

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

下面是包含结果的数组

$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中,该表应该是三行,但只有一行插入表中并显示而不是三行,以防用户在文本框中输入任何值。

4

1 回答 1

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) . ";";
于 2013-07-14T17:51:35.670 回答