Insert array into database using PHP

I have x, y and z which are arrays. The data is displayed correctly, but I cannot force it to be inserted into my database. It inserts the correct number of rows as all 0, and not the int values ​​entered by the user. Here is the 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();
}

I get this error: Note: an array to convert strings to

It is on all three lines of bindValue

I know that foreach is wrong, but this is the only cycle I have encountered. Gives me the correct number of rows, but only inserts 0 into the database.

+4
source share
2 answers

You need to insert the value of x with y, z at the same index as

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

,

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

:

$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();
}
0

Source: https://habr.com/ru/post/1676431/


All Articles