使用execute($ array)插入时出错

时间:2013-07-17 19:46:55

标签: php arrays pdo insert

我有一张桌子

percentile      int(3)  No           
FoSW            int(3)  Yes     NULL     
dfLR            int(3)  Yes     NULL     
FoA             int(3)  Yes     NULL     
SoG             int(3)  Yes     NULL     
RST             int(3)  Yes     NULL     
SSW             int(3)  Yes     NULL    
total           int(3)  No  

和一个数组:

Array
(
    [percentile] => 99
    [FoSW] => 125
    [DfLR] => 110
    [FoA] => 60
    [SoG] => 120
    [RST] => 40
    [SSW] => 45
    [total] => 500
)

这段代码因某种原因无效...... Catch不会抛出错误。只是我的if语句回声错误...

if ($_POST['percent']=='add'){
    try{
        $post = $_POST;
        unset($post['percent']);

        $sth = $dbh->prepare("INSERT INTO percentiles (percentile, FoSW, dfLR, FoA, SoG, RST, SSW, total) VALUES (?,?,?,?,?,?,?,?)");

        if ($sth->execute($post)){
            echo 'done<br/>';
        }

        else echo 'error';
    }

    catch(PDOException $e){
        echo 'error'.$e;
    }
}

1 个答案:

答案 0 :(得分:1)

您的数组$post匹配INSERT操作所需的八个值,但数组应该用整数索引,而不是关联数组/字典。

Array
(
    [percentile] => 99
    [FoSW] => 125
    [DfLR] => 110
    [FoA] => 60
    [SoG] => 120
    [RST] => 40
    [SSW] => 45
    [total] => 500
)

如果您按以下方式更改prepare()来电,则上述数组将有效:

$sth = $dbh->prepare("INSERT INTO percentiles 
        (percentile, FoSW, 
        dfLR, FoA, 
        SoG, RST, 
        SSW, total) 
    VALUES
        (:percentile, :FoSW, 
        :DfLR, :FoA, 
        :SoG, :RST, 
        :SSW, :total)");