【问题标题】:insert query mysql throws PDO::exec() expects exactly 1 parameter, 2 given插入查询 mysql 抛出 PDO::exec() 恰好需要 1 个参数,给定 2 个
【发布时间】: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


    【解决方案1】:

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

    也没有$conn-&gt;fetch() 方法。 fetch()PDOStatement 类的一个方法,您可以将它用于准备好的语句或查询的结果。但是你不需要执行查询来获取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);
            }
        }
    }
    

    【讨论】:

    • 感谢您为我指明了正确的方向,foreach 语句(您已修复)分支为 if 语句...我将尝试根据您前半部分的结构来修改 if 语句。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    相关资源
    最近更新 更多