使大型Mysqli插入更有效

时间:2013-02-08 13:07:26

标签: php mysql performance mysqli

我有几个需要插入数据库的大表单。

我目前正在这样做

$stmt = $memberMysqli->prepare("INSERT INTO questionnairebespokeexerciseplan(userid,date,naturalbodytype,framesizewrist,framesizeelbow,fitnessgoals,workpattern,sleephours,runningbarriers,workcommute,workdistance,smoke,biomechanicalissues,limitingillness,reletivesheartproblems,birthlast12months,recurringinjuries,regularmedication,pregnant,anythingelsehealth,gymmember,runoutdoors,wouldyouliketorunoutdoors,homeequipments,whattypeequipment,exercisetime,heartratemonitor,restingheartrate,actualheartrate,maxheartrate,heartratesteadyrun,heartratebreathless,trainingshoes,preferredexercisetype,exerciseclasses,classdays,bike,bikemodel,runlunchtimebeforework,clubmember,clubschedule,personaltraining,otherheartrate,foottype) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

$stmt->bind_param('ssssssssssssssssssssssssssssssssssssssssssss',
                                                $_POST['userid'],
                                        $date,
                                        $_POST['naturalbodytype'],
                                        $_POST['framesizewrist'],
                                        $_POST['framesizeelbow'],
                                        $_POST['fitnessgoals'],
                                        $_POST['workpattern'],
                                        $_POST['sleep'],
                                        $_POST['runbarriers'],
                                        $_POST['workcommute'],
                                        $_POST['workmiles'],
                                        $_POST['smoke'],
                                        $_POST['biomechanical'],
                                        $_POST['illnesses'],
                                        $_POST['heartcondition'],
                                        $_POST['givenbirth'],
                                        $_POST['injuries'],
                                        $_POST['medication'],
                                        $_POST['pregnant'],
                                        $_POST['anythingelse'],
                                        $_POST['gymmember'],
                                        $_POST['runoutdoors'],
                                        $_POST['liketorunoutside'],
                                        $_POST['homeequipment'],
                                        $_POST['equipment'],
                                        $_POST['besttime'],
                                        $_POST['heartratemonitor'],
                                        $_POST['restingheartrate'],
                                        $_POST['actualheartrate'],
                                        $_POST['actualmaxheartrate'],
                                        $_POST['heartratesteadyrun'],
                                        $_POST['heartratebreathless'],
                                        $_POST['trainingshoes'],
                                        $_POST['preferredexersize'],
                                        $_POST['classes'],
                                        $_POST['classdays'],
                                        $_POST['bike'],
                                        $_POST['whatbike'],
                                        $_POST['beforeworklunchtime'],
                                        $_POST['clubmember'],
                                        $_POST['clubschedule'],
                                        $_POST['personaltrainer'],
                                        $_POST['otherheartrate'],
                                        $_POST['foottype']
                                        );

我只是在考虑是否有更好/更快的方式来做这件事?

目前需要一些时间来创建它并在事情不正确时进行调试同样耗费时间。

2 个答案:

答案 0 :(得分:1)

您可以自己编写一个脚本来自动生成此语句。 确保您保持字段名称一致(在您的表单和数据库中),然后像这样的代码可能适合您:

// ADD ALL YOUR FIELDS TO THIS ARRAY. 
// THIS SHOULD BE THE ONLY PART OF THE CODE 
// WHICH YOU WILL HAVE TO MAINTAIN.

$fields = array(
'userid',
'date',
'naturalbodytype',
'framesizewrist' //etc. add all your fields
);

//you may have to adjust some fields manually:

$_POST['date'] = $date;


//HERE IS WHERE THE AUTOMATED PART STARTS
//YOU WONT EVER HAVE TO TOUCH THIS PART

//writing all fields for the query
$all_fields = implode(', ' $fields); 

//writing the correct number of questionmarks    
$questionmarks = str_repeat('?, ' count($fields)-1).'?';

//generate your statement
$stmt = $memberMysqli->prepare(
"INSERT INTO questionnairebespokeexerciseplan
 ( {$all_fields} ) 
 VALUES 
 ( {$questionmarks} )");

//write the correct amount of 's' characters for parameter types
$parameter_types = str_repeat('s' count($fields));


//generate the code which will write the parameters

$all_fields_to_bind=array();

foreach($fields as $field)
{
    $all_fields_to_bind[] = "\$_POST['". $field. "']";
}

//generate the code to be evaluated
$eval_statement = '$stmt->bind_param($parameter_types,'.implode(', ', $all_fields_to_bind).');';

//evaluate (meaning execute) your dynamically generated code
eval($eval_statement);

我没有测试这个,可能仍然存在一些语法错误。我也不知道它有多安全!但它应该工作,因为我使用类似的SELECT语句。

答案 1 :(得分:-1)

SafeMysql可以使您的代码缩短3倍。虽然列出所有允许的字段是必不可少的。

$allowed = explode(",","userid,date,naturalbodytype,framesizewrist,framesizeelbow,fitnessgoals,workpattern,sleephours,runningbarriers,workcommute,workdistance,smoke,biomechanicalissues,limitingillness,reletivesheartproblems,birthlast12months,recurringinjuries,regularmedication,pregnant,anythingelsehealth,gymmember,runoutdoors,wouldyouliketorunoutdoors,homeequipments,whattypeequipment,exercisetime,heartratemonitor,restingheartrate,actualheartrate,maxheartrate,heartratesteadyrun,heartratebreathless,trainingshoes,preferredexercisetype,exerciseclasses,classdays,bike,bikemodel,runlunchtimebeforework,clubmember,clubschedule,personaltraining,otherheartrate,foottype");

$data = $db->filterArray($_POST,$allowed);
$sql = "INSERT INTO questionnairebespokeexerciseplan SET ?u";
$db->query($sql, $data);