PDO基于数组键作为列名插入

时间:2016-01-05 08:26:44

标签: php pdo

我有一个PDO插入语句,用于从表单提交中更新数据库表。有很多领域。我故意使用与html输入名称相同的列名。是否有更简洁的方法来布置此代码?目前我有30多个<div class="col-md-3"> @Html.DropDownListFor(model => model.Town_State, ilia_Common.ilia.Fill_Town(), new { @Id = "rdTown", @class = "form-control chosen-select", style = "width:150px" }) @Html.ValidationMessageFor(model => model.Town_State, null, new { @class = "text-danger" }) </div> @Html.LabelFor(model => model.City_State, htmlAttributes: new { @class = "control-label col-md-3" }) <div class="col-md-3"> @Html.DropDownListFor(model => model.City_State, ilia_Common.ilia.Fill_City(), new { Id = "rdCity", @class = "form-control chosen-select ", style = "width:150px" }) @Html.ValidationMessageFor(model => model.City_State, null, new { @class = "text-danger" }) </div> 个变量,并且更喜欢通过某种循环获得更清晰的解决方案。

这是我目前的实施,例如,我只包含了一些字段。

package MyApp;
use base 'Wx::App';

use strict;
use warnings;
use Wx;
use aliased 'Widgets::Forms::MyWxFrame';

sub new {

    my $self = shift;
    $self = {};
    $self = Wx::App->new( \&OnInit );
    bless($self);

    $self->{"windowNumber"} = shift;

    my $mainFrm = MyWxFrame->new(
        undef,                     
        -1,                        
        "My app - ".$self->{"windowNumber"},
        &Wx::wxDefaultPosition
    );

    my $button = Wx::Button->new( $mainFrm, -1, "Test btn", );
    Wx::Event::EVT_BUTTON( $button, -1, sub { __OnClick( $self, @_ ) } );

    $mainFrm->Show(1);
    return $self;
}

sub OnInit {
    return 1;
}

sub __OnClick {
    my $self  = shift;
    my $btn   = shift;
    my $event = shift;

    print $self->{"windowNumber"};
}

my $myApp = MyApp->new(1);
my $myApp2 = MyApp->new(2);


$myApp->MainLoop;

3 个答案:

答案 0 :(得分:1)

尝试以下内容

$postarr = array('Col1', 'ColABC', 'Col123', 'ColFoo', 'ColDEF'); //<---- defined all the form elements you like to get from post
$sql = ''; $param = array();
foreach($postarr as $k){
    $sql .= $k.'=:'.$k.','; // setting up placeholders for columns we are goign to update or get value from $_POST data
    $param[$k] = $_POST[$k]; // setting up param array argument for execute() function
}
$sql = substr($sql,0,-1); // <--- remove last ,
$stmt = $dbh->prepare("INSERT INTO myTable SET " . $sql);
$stmt->execute($param);

答案 1 :(得分:0)

以下未经过测试,但您可以尝试这样的事情。

<form id='sqlpost' method='post' action='/test/target.php'>
    <h1>SQL Post</h1>       
    <input type='text' name='user' value='fred'/>
    <input type='text' name='name' value='frederick'/>
    <input type='text' name='email' value='fred@bedrock.com'/>

    <input type='text' name='age' value='21'/>
    <input type='text' name='sex' value='male'/>

    <input type="submit" name="subform" value="Submit"/>
</form>


/*
target.php
----------
*/

if( $_SERVER['REQUEST_METHOD']=='POST' ){

    $known=array('user','email','name');
    $postdata=array();


    foreach( $_POST as $field => $value ){
        if( in_array( $field, $known ) ) $postdata[ $field ]=$value;
    }

    $keys=array_keys( $postdata );
    $values=array_values( $postdata );              

    $sql='insert into myTable (`'.implode('`,`',$keys).'`) values (:'.implode(':',$keys).')';
    echo $sql;
}

答案 2 :(得分:0)

将所有值都放入数组$ input中。并使用list()如下。

$InputArray['cal1'] =  $_POST['cal1'];
$InputArray['collabc'] =  $_POST['collabc'];
$InputArray['col123'] =  $_POST['col123'];
$InputArray['clofoo'] =  $_POST['clofoo'];
$InputArray['coldef'] =  $_POST['coldef'];

if (count($inputArray) > 0) {
        while (list($key, $val) = each($inputArray)) {
            if(!empty($val)){
                $fields.= $key . ',';
                $valset.= "'". $val ."',";
            }
        }
    }   

    $fields = trim($fields, ',');
    $valset = trim($valset, ',');
    $sql = "INSERT INTO $tableName ($fields) VALUES ($valset)";

    $stmt = $this->dbCon->prepare($sql);
    $stmt->execute($inputArray);