简体   繁体   中英

Uploading the image file to the server doesn't work

I was trying to upload a BLOB with prepared statements to the MYSQL database, but I can't find the reason why it isn't working. Could somebody explain me the reason?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registrieren</title>
</head>
<body>
<header>

    <?php
    if (isset($_POST['submit'])) {
        require_once "db_connect.php";

        //Arbeit mit prepared Statements, da diese gegen SQL-Injections sicher sind im Gegensatz zum Escapen
        $stmt = $mysqli->prepare("INSERT INTO Bild (Bild_ID, Inhalt, Info) VALUES (?, ?, ?)");
        $stmt->bind_param("ibs", $picID, $image, $info);
        // set parameters and execute
        $picID = NULL;
        $image = file_get_contents($_FILES['userPic']['name']);
        echo($image);
        $info = "just an example";
        $stmt->execute();

        echo "New records created successfully";
        $stmt->close();
        $mysqli->close();
    }
    ?>
</header>
<main>
    <form action="" method="post" enctype="multipart/form-data">
        <input id="UserPicUpload" type="file" name="userPic" accept="image/*">
        <button id="send" type="submit" name="submit" >Bild Hochladen</button>
    </form>
</main>
</body>
</html>

Several mistakes here...

  1. When you bind your parameters, they aren't even defined - you define image and picID and info after you bind it.
  2. The uploaded file's content is available using the tmp_name key.

Regarding the picID: Depending on the use case, you may set this to AUTO_INCREMENT in your database. Since the type is an integer, I doubt that you actually want to set these numbers manually.

This would leave us with the following code:

    $image = file_get_contents($_FILES['userPic']['tmp_name']);
    $info = "just an example";
    $stmt = $mysqli->prepare("INSERT INTO Bild (Inhalt, Info) VALUES (?, ?)");
    $stmt->bind_param("bs", $image, $info);
    $stmt->execute();
    echo "New records created successfully";

Another word: Name your stuff either German or English and use that globally, but don't mix up the languages. It's rather confusing to have the Bild_ID named picID .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM