【发布时间】:2021-01-26 06:07:03
【问题描述】:
我拼凑了一些从互联网上收集的代码:我正在尝试扫描目录以将文件名和索引插入 MariaDB 表。我的最后一个障碍似乎是这个 PDO 错误:PDO::exec() 只需要 1 个参数,第 55 行给出了 2 个参数。我在 line(55) 上标记了 '//error throw here'。 我的新手猜测是它不喜欢在[]中转义的参数??
如上所述,新手在这里... 非常感谢任何见解/帮助。提前致谢。
<?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);
【问题讨论】:
标签: php mysql pdo sql-insert