【问题标题】:I am getting an error when inserting with execute($array)使用 execute($array) 插入时出现错误
【发布时间】:2013-07-16 13:02:52
【问题描述】:

我有一张桌子

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;
    }
}

【问题讨论】:

  • 您有效地将 $_POST 分配给您的占位符 - $_POST 中有 8 个字段吗?它们是八阶吗?
  • @SmithSmithy - 我可以看到一个关联数组,它有 8 个键值对。那是16个元素。您可能只想获取 $_POST; 的值。但是如果您明确分配值,维护起来会容易得多。如果您将来更改表单,即使您移动了几个字段,此代码也会中断。
  • 另请参阅stackoverflow.com/a/15990858/689579,了解获取 PDO 错误消息。
  • @SmithSmithy - 你可以不用$sth-&gt;execute(array($_POST['percentile], $_POST['FoSW'].....,在执行中明确命名每个 $_POST 字段。
  • 如果你有 php>=5.2 否 - 来自 php.net/manual/en/pdostatement.execute.php Changelog :: The keys from input_parameters must match the ones declared in the SQL. Before PHP 5.2.0 this was silently ignored.

标签: php arrays pdo insert


【解决方案1】:

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

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)");

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多