Skip to content

sqlite non-sequential keys in array throws error when passed to execute with PDO #16081

@truecastdesign

Description

@truecastdesign

Description

PHP 8.2

$dsn = 'sqlite:'.$config->database;

$this->obj = new PDO($dsn);
$this->obj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

The following code:

<?php
// Assuming $pdo is your PDO database connection object
$values
array(12) {
  [0]=>
  string(23) "/powersports-batteries/"
  [1]=>
  string(32) "/powersports-batteries/-catelist"
  [2]=>
  string(31) "/powersports-batteries/-sideNav"
  [3]=>
  string(10) "/testing1/"
  [4]=>
  string(19) "/testing1/-catelist"
  [5]=>
  string(18) "/testing1/-sideNav"
  [6]=>
  string(19) "/testing1/testing4/"
  [7]=>
  string(28) "/testing1/testing4/-catelist"
  [8]=>
  string(27) "/testing1/testing4/-sideNav"
  [12]=>
  string(24) "/testing1/testing5-copy/"
  [13]=>
  string(33) "/testing1/testing5-copy/-catelist"
  [14]=>
  string(32) "/testing1/testing5-copy/-sideNav"
}

// Notice that array keys are non-sequential after 8. I had removed some items from the array and then tried to use that to delete the rows with those titles. Kept getting that error. 

$sql = "DELETE FROM `data` WHERE title IN (" . str_repeat('?,', count($values) - 1) . '?)';
$stmt = $pdo->prepare($sql);

if ($stmt->execute($values)) {
    echo "Rows deleted: " . $stmt->rowCount();
} else {
    $errorInfo = $stmt->errorInfo();
    echo "Error: " . $errorInfo[2];
}

Resulted in this output:

SQLSTATE[HY000]: General error: 25 column index out of range
Error: column index out of range

But I expected this output instead:

Rows deleted: [expected number of rows, e.g., 12]

The $stmt->execute($values) method should use a foreach instead of a for loop or run a:
$values = array_values($values); over the incoming array so people don't have to bang their head against a way trying to figure out why their query will not run.

PHP Version

PHP 8.2

Operating System

CloudLinux v9.4.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions