Home > database >  Error when uploading image into phpmyadmin using PDO in php
Error when uploading image into phpmyadmin using PDO in php

Time:05-10

I am trying to learn inserting image into phpmyadmin my db structer:

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

my code is:

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

my error on submit:

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

Any ideas what is wrong there when trying to upload a png file?

CodePudding user response:

The problem is that you're sending an empty string at the 'id' value:

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

The correct would be to tell the columns with the values to add not sending anything for the 'id' column since it's is an auto increment

$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);
  • Related