数组到字符串转换错误/问题

时间:2015-06-23 20:42:59

标签: php sql arrays

我是一个PHP新手,并继续获取" PHP注意:数组到字符串转换"当我尝试给我这个代码循环通过INSERTING项目到数据库。我需要循环,因为我使用ajax脚本动态读取表单字段数据,当你添加/删除字段,并推动它通过PHP,因为$ idx允许$ idx递增,允许我动态添加INSERTS。

有谁知道如何更改它以使其工作,请告诉我你是如何/为什么/你做了什么,以便我可以学习以备将来使用。谢谢!

我的PHP:

$sql = "INSERT INTO items (WID, model, description, cost, retail, qty) values(?, ?, ?, ?, ?, ?);";
        $q = $pdo->prepare($sql);
        $idx = 0;
        foreach ($Model as $model_idx) {
            $q->execute(array($wid,$model_idx, $Description[$idx], $Cost[$idx], $Retail[$idx], $Quantity[$idx]));
            $idx++;
        }

我的Php / Html:

<div class="control-group <?php echo !empty($ModelError)?'error':'';?>">
                                    <div class="controls">
                                        <input type="text" data-type="model" name="model[]" id="model_1" placeholder="Model" value="<?php echo !empty($Model)?$Model:'';?>" class="form-control autocomplete_txt" autocomplete="off">
                                            <?php if (!empty($ModelError)): ?>
                                                <span class="help-inline"><?php echo $ModelError;?></span>
                                            <?php endif; ?>
                                    </div>
                            </div>

验证/字符串输出:

if ( !empty($_POST)) {
        // keep track validation $

        $ModelError       = null;
        $DescriptionError = null;
        $CostError        = null;
        $RetailError      = null;
        $QuantityError    = null;

        // keep track post values

        $Model        = $_POST['model'];
        $Description  = $_POST['description'];
        $Cost         = $_POST['cost'];
        $Retail       = $_POST['retail'];
        $Quantity     = $_POST['quantity'];

        // validate input
        $valid = true;
        if (empty($Model)) {
            $ModelError = 'Please enter Model';
            $valid = false;
        }

1 个答案:

答案 0 :(得分:1)

正如您所述,问题是Array to String conversion,这意味着您的代码

$sql = "INSERT INTO items (WID, model, description, cost, retail, qty) values(?, ?, ?, ?, ?, ?);";
        $q = $pdo->prepare($sql);
        $idx = 0;
        foreach ($Model as $model_idx) {
            $q->execute(array($wid,$model_idx, $Description[$idx], $Cost[$idx], $Retail[$idx], $Quantity[$idx]));
            $idx++;
        }

此处$Model不是一个数组,所以请尝试按echo "<pre/>";print_r($Model);var_dump($Model);打印出来并检查是否有阵列?

如果没有,请检查您的HTML代码并尝试解决它。​​

此外,我不确定您是如何获得这些变量的$wid,$model_idx, $Description[$idx], $Cost[$idx], $Retail[$idx], $Quantity[$idx]