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

smdnsysy  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(135)

我正在尝试学习将图像插入到***phpmyadmin***my db structer中:

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文件?

ogq8wdun

ogq8wdun1#

问题是您在'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);

相关问题