通过PHP填充数据库

时间:2013-01-01 13:58:12

标签: php mysql phpmyadmin xampp

我正在尝试为项目填充数据库。我已经安装了Xampp,我使用phpmyadmin通过GUI访问数据库。数据库有点大,包括评估特定问题的经济替代方案所需的经济因素。 PHP代码:

function _fp($n,$i){
return number_format((pow((1+$i),$n)),5);
}

function _pf($n,$i){
return number_format((1/_fp($n,$i)),5);
}

function _pa($n,$i){
return number_format(((pow((1+$i),$n)-1)/($i*pow((1+$i),$n))),5);
}

function _ap($n,$i){
return number_format((1/_pa($n,$i)),5);
}

function _fa($n,$i){
return number_format(((pow((1+$i),$n)-1)/$i),5);
}

function _af($n,$i){
return number_format((1/_fa($n,$i)),5);
}

function _pg($n,$i){
return number_format(((pow((1+$i),$n)-$i*$n-1)/($i*$i*pow((1+$i),$n))),5);
}

function _ag($n,$i){
return number_format((1/$i-$n/(pow((1+$i),$n)-1)),5);
}

$connection=mysql_connect("localhost","root",'');
if($connection){
$db=mysql_select_db("comp_interest_fact");
if(!$db)
    echo "Failed to select 'comp_interest_fact'.\n";
}
else
echo "Failed to connect to database.\n";

$percentage=array('0_25'=>.0025,
    '0_5'=>.005,
'0_75'=>.0075,
'1'=>.01,
'1_25'=>.0125,
'1_5'=>.015,
'2'=>.02,
'3'=>.03,
'4'=>.04,
'5'=>.05,
'6'=>.06,
'7'=>.07,
'8'=>.08,
'9'=>.09,
'10'=>.1,
'11'=>.11,
'12'=>.12,
'13'=>.13,
'14'=>.14,
'15'=>.15,
'16'=>.16,
'18'=>.18,
'20'=>.20,
'22'=>.22,
'24'=>.24,
'25'=>.25,
'30'=>.3);
reset($percentage);
while(list($key,$value)=each($percentage)){
$table="percent_$key";
for($k=1;$k<=50;$k++){
    $fp=_fp($k,$value);
    $pf=_pf($k,$value);
    $af=_af($k,$value);
    $fa=_fa($k,$value);
    $ap=_ap($k,$value);
    $pa=_pa($k,$value);
    $pg=_pg($k,$value);
    $ag=_ag($k,$value);
    mysql_query("INSERT INTO $table         VALUES($k,".$fp.",".$pf.",".$af.",".$fa.",".$ap.",".$pa.",".$pg.",".$ag.")");
}
}
mysql_close($connection);

这个脚本的问题是,一旦我运行它,comp_interest_fact中的表就没有全部50行。实际上它们应该是因为for循环需要50次迭代才能进行50次INSERT操作。我找不到问题。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

将插入条件更改为:

 mysql_query("INSERT INTO $table VALUES($k,".$fp.",".$pf.",".$af.",".$fa.",".$ap.",".$pa.",".$pg.",".$ag.")") or die(mysql_error());

或更好:

mysql_query("INSERT INTO $table VALUES ($k, $fp, $pf, $af, $fa, $ap, $pa, $pg, $ag)") or die(mysql_error());

同样命名你当前拥有它们的函数几乎是任何未来的开发人员都要处理你的代码。

突出Hanky Pankys评论:

In Addition to this suggestion, please also note that this code will produce 1350 INSERT operations and not 50. It will run 50 * 27 Times as per your code

如果您的$ k是您的主键,那么您将在每次运行时获得被覆盖的值。你应该有一个自动公钥。