insert query mysql throws PDO::exec() 正好需要 1 个参数,给定 2 个

insert query mysql throws PDO::exec() expects exactly 1 parameter, 2 given

我拼凑了一些从互联网上收集的代码:我正在尝试扫描目录以将文件名和索引插入 MariaDB table。我的最后一个障碍似乎是这个 PDO 错误:PDO::exec() 恰好需要 1 个参数,第 55 行给出了 2 个参数。我在 line(55) 上标记了“//此处抛出错误”。 我的新手猜测是它不喜欢[]中转义的参数??

如上所述新手在这里... 非常感谢任何 insight/help。提前致谢。

<?php

    $host = 'localhost';
    $dbname = 'dirdb';
    $username = 'root';
    $password = '';

    // Create connection
try {
  $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}   

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$dir = './recipes';

$GLOBALS['I'] = 0; // root folder given index 0

function dirToArray( $dir , $parent) {
    $result = array();
    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {
        if (!in_array($value, array(".", "..")))  {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){

                $result[$value] = [++$GLOBALS['I']]; // add folder index
                $result[$value][] = $parent; // add parent folder index

                $result[$value][] = dirToArray($dir . DIRECTORY_SEPARATOR . $value, $GLOBALS['I']);
            } else {
                $result[] = $value;
            }
        }
    }
    return $result;
}

$res = dirToArray($dir, $GLOBALS['I']);


function dirToDb($res, $parentId = 0)
{global $conn;
    foreach ($res as $key => $value) {
        if (is_array($value))  {
            $conn->exec ("insert into sp_files (path, parentId) VALUES (?, ?)", [$key, $parentId]);  //error thrown here
            dirToDb($value, $conn->fetch("SELECT LAST_INSERT_ID()"));
        } else {
            $conn->exec ("insert into sp_files (path, parentId) VALUES (?, ?)", [$value, $parentId]);
        }
    }
}

//$res = dirToArray($dir);

dirToDb($res);

您不能使用 $conn->exec() 来执行带参数的查询。您必须使用 prepare() 创建语句,然后执行准备好的语句。

也没有$conn->fetch()方法。 fetch()PDOStatement class 的一种方法,您可以将它与准备好的语句或查询结果一起使用。但是你不需要执行查询来获取 LAST_INSERT_ID(),PDO 有一个 insertId() 方法来实现这个。

function dirToDb($res, $parentId = 0) {
    global $conn;
    $stmt = $conn->prepare("insert into sp_files (path, parentId) VALUES (?, ?)");
    foreach ($res as $key => $value) {
        $stmt->execute([$key, $parentId]); 
        if (is_array($value))  {
            dirToDb($value, $stmt->insertId);
        }
    }
}