使用PHP

时间:2017-05-05 04:56:52

标签: php mysql arrays

我有x,y和z是数组。数据显示正常但我无法将其插入到我的数据库中。它插入适当数量的行作为全0,而不是用户输入的int值。这是php。

$x = $_POST['x'];
$y = $_POST['y'];
$z = $_POST['z'];


foreach($x as $result){
    $query = 'INSERT INTO table
            (x, y, z)
                VALUES (:x, :y, :z)';
    $statement = $db->prepare($query);
    $statement->bindValue(':x', $x);
    $statement->bindValue(':y', $y);
    $statement->bindValue(':z', $z);
    $statement->execute();
    $statement->closeCursor();
}

我收到此错误:注意:

中的数组到字符串转换

它位于所有3个bindValue行

我知道foreach错了,但那是我唯一接近的循环。给我适当的行数,但只将0插入数据库。

2 个答案:

答案 0 :(得分:2)

您必须在相同的索引上插入带有y,z的x值,例如

foreach($x as $key=>$xval){
    $query = 'INSERT INTO table
            (x, y, z)
                VALUES (:x, :y, :z)';
    $statement = $db->prepare($query);
    $statement->bindValue(':x', $xval);
    // check if y value exist on same key
    $statement->bindValue(':y', isset($y[$key]) ? $y[$key] : '');
    // check if z value exist on same key
    $statement->bindValue(':z', isset($z[$key]) ? $z[$key] : '');
    $statement->execute();
    $statement->closeCursor();
}

Bulk Insert Prepared Statements您可以尝试批量插入,例如

try {
    $sql="INSERT INTO table (x, y, z) VALUES ";
        $insertQuery    = array();
        $insertData     = array();
        foreach ($x as $key=>$xval ) {
            $insertQuery[] = '(?,?,?)';
            $insertData[] = $xval;
            $insertData[] = isset($y[$key])?$y[$key]:'';
            $insertData[] = isset($z[$key])?$z[$key]:'';
        }

        if (!empty($insertQuery)) {
            $sql .= implode(', ', $insertQuery);
            $stmt = $this->db->prepare($sql);
            $stmt->execute($insertData);
            $stmt->closeCursor();
        }
 } catch (PDOException $e) {
        error_log('Error reading the session data table in the session reading method.');
        error_log(' Query with error: '.$sql);
        error_log(' Reason given:'.$e->getMessage()."\n");
        return false;
 }

答案 1 :(得分:0)

以下是我对这类问题简单直接理解的逻辑:

$sizex = count($x);
$sizey = count($y);
$sizez = count($z); 

$maxsize = max($sizex,$sizey,$sizez);
for ($i = 0; $i < $maxsize; $i++) {
  $query = 'INSERT INTO table
            (x, y, z)
                VALUES (:x, :y, :z)';
    $statement = $db->prepare($query);
    $statement->bindValue(':x', isset($x[$i])?$x[$i]:''));
    // check if y value exist on same key
    $statement->bindValue(':y', isset($y[$i])?$y[$i]:'');
    // check if z value exist on same key
    $statement->bindValue(':z', isset($z[$i])?$z[$i]:'');
    $statement->execute();
    $statement->closeCursor();
}