在 php 中使用 PDO 将图像上传到 phpmyadmin 时出错

Error when uploading image into phpmyadmin using PDO in php

我正在尝试学习将图像插入 phpmyadmin 我的数据库结构:

id int(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
mime VARCHAR(255),
data BLOB

我的代码是:

        <?php
        ini_set('display_errors', '1');
        ini_set('display_startup_errors', '1');
        error_reporting(E_ALL);
        $dbh = new PDO("mysql:host=localhost;dbname=mydata", "root", "123456");

        if(isset($_POST['btn'])){
            $name = $_FILES['myfile']['name'];
            $type = $_FILES['myfile']['type'];
            $data = file_get_contents($_FILES['myfile']['tmp_name']);
            $stmt = $dbh->prepare("INSERT INTO myblob VALUES('',?,?,?)");
            $stmt->bindParam(1,$name);
            $stmt->bindParam(2,$type);
            $stmt->bindParam(3,$data);
            $stmt->execute();
        }
        ?>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="myfile" />
            <button name="btn">Upload</button>
        </form>

我的提交错误:

Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column `mydata`.`myblob`.`id` at row 1

尝试上传 png 文件时有什么问题吗?

问题是您在 'id' 值处发送空字符串:

$stmt = $dbh->prepare("INSERT INTO myblob VALUES('',?,?,?)");

正确的做法是告诉要添加值的列不要为 'id' 列发送任何内容,因为它是自动递增的

$stmt = $dbh->prepare(INSERT INTO myBlob(name, type, data) VALUES(:name, :type, :data)
$stmt->bindParam('name',$name);
$stmt->bindParam('type',$type);
$stmt->bindParam('data',$data);