在多行中插入多个值

时间:2018-06-11 16:41:40

标签: php mysql pdo

如何在多行中插入多个图像?我已经通过下面的查询插入了一个图像。现在我想再插入一个图像,名为“imagetwo”的行。

如何针对两行修改此查询图片图片

<?php   

    public function insertName($data,$file){

        $name = $data['name'];

        $permited  = array('jpg', 'jpeg', 'png', 'gif');
        $file_name = $file['image']['name'];
        $file_size = $file['image']['size'];
        $file_temp = $file['image']['tmp_name'];


        $div = explode('.', $file_name);
        $file_ext = strtolower(end($div));
        $unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
        $uploaded_image = "upload/".$unique_image;


        if ($name == "") {
            $msg = 'Name Field Must Not Be Empty';
            return $msg;
        } else {
            move_uploaded_file($file_temp, $uploaded_image);

            $stmt = $this->pdo->prepare("INSERT INTO name(`name`, `image`) VALUES (:name, :uploaded_image)");
            $stmt->bindParam(":name", $name);
            $stmt->bindParam(":uploaded_image", $uploaded_image);
            $stmt->execute();
            // return $stmt;

            if ($stmt) {
                $msg = 'Name Inserted Secessfully';
                return $msg;
            } else {
                $msg = 'Name Not Inserted Secessfully';
                return $msg;
            }
        }

    } 

2 个答案:

答案 0 :(得分:-1)

我想你没有看过评论。虽然我决定以程序的方式向你展示一个例子。应该很容易使函数适应代码体系结构(可能是MVC)。

起点 - 最重要的一点 - 是$_FILES数组的规范化PSR-7: 1.6 Uploaded files中描述的最好(也很简单) - 如果您阅读并理解前两段和前两个代码块就足够了。在规范化之后,可以直观地应用其余步骤:每个文件都上传并保存为db表中的记录(如果在上载过程中没有发生错误)。

代码尝试上传多个文件。如果在上传文件(来自许多文件)期间出现问题 - 例如最多超出大小,或无效扩展等等 - 然后显示该文件的相应错误消息,并且不保存文件 - 既不在文件系统中也不在数据库中。保存其上载过程不会导致错误的其他文件。换句话说:仅当成功上载并保存所有文件时,才会显示成功消息。否则,将显示(仅)“制造麻烦”文件的错误消息列表。

您可以按原样运行代码。所有文件都位于同一目录中。

我不知道你的$name参数是什么。所以我只使用了文件名。

<强> upload.php的

<?php
require_once 'config.php';
require 'connection.php';
require_once 'functions.php';

$allFilesUploadedAndSaved = FALSE;

// Operations upon form submission.
if (isset($_POST['submit'])) {
    if ($_FILES) {
        // Normalize the posted files array.
        $normalizedFiles = normalizeUploadedFiles($_FILES['files']);

        // Upload and save each file.
        foreach ($normalizedFiles as $normalizedFile) {
            $uploadedAndSaved = uploadAndSaveFile($connection, $normalizedFile);

            if ($uploadedAndSaved !== TRUE) {
                $errors[] = $uploadedAndSaved;
            }
        }

        if (!isset($errors)) {
            $allFilesUploadedAndSaved = TRUE;
        }
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo - Upload multiple files</title>

        <!-- CSS assets -->
        <link href="upload.css" type="text/css" rel="stylesheet">
    </head>
    <body>

        <div class="page-container">

            <form action="" method="post" enctype="multipart/form-data">
                <div class="messages">
                    <?php
                    if (isset($errors)) {
                        foreach ($errors as $error) {
                            ?>
                            <div class="message danger">
                                <?php echo $error; ?>
                            </div>
                            <?php
                        }
                    } elseif ($allFilesUploadedAndSaved) {
                        ?>
                        <div class="message success">
                            All files successfully uploaded.
                        </div>
                        <?php
                    }
                    ?>
                </div>

                <div class="form-group">
                    <label for="myFiles">My Files</label>
                    <input type="file" id="myFiles" name="files[]" multiple class="form-control">
                </div>

                <div class="form-group">
                    <button type="submit" id="submit" name="submit" value="upload">
                        Upload
                    </button>
                </div>
            </form>

        </div>

    </body>
</html>

<强>的functions.php

<?php

/**
 * Normalize the uploaded files array.
 *
 * NB: Read the link!
 *
 * @link https://www.php-fig.org/psr/psr-7/#16-uploaded-files PSR-7: 1.6 Uploaded files.
 * @param array $files Uploaded files array.
 * @return array Normalized files array.
 */
function normalizeUploadedFiles($files) {
    $normalizedFiles = [];

    foreach ($files as $filesKey => $filesItem) {
        foreach ($filesItem as $itemKey => $itemValue) {
            $normalizedFiles[$itemKey][$filesKey] = $itemValue;
        }
    }

    return $normalizedFiles;
}

/**
 * Upload and save an uploaded file.
 *
 * @param PDO $connection Db connection.
 * @param array $file The file to upload.
 * @return string|TRUE TRUE if the file upload is successful, a corresponding error message otherwise.
 */
function uploadAndSaveFile($connection, $file) {
    $name = $file['name'];
    $type = $file['type'];
    $tmpName = $file['tmp_name'];
    $error = $file['error'];
    $size = $file['size'];

    /*
     * Check for upload errors.
     *
     * @todo Return a description message corresponding to the specific error code!
     * @link https://secure.php.net/manual/en/features.file-upload.errors.php Error Messages Explained.
     */
    if ($error !== UPLOAD_ERR_OK) {
        return sprintf('An error occured regarding the file %s. Error code: %s'
                , $name
                , $error
        );
    }

    // Validate the file size.
    if ($size > UPLOAD_MAX_FILE_SIZE) {
        return sprintf('The size of the file "%s" exceeds the maximal allowed size (%s Byte).'
                , $name
                , UPLOAD_MAX_FILE_SIZE
        );
    }

    // Validate the file type.
    if (!in_array($type, UPLOAD_ALLOWED_MIME_TYPES)) {
        return sprintf('The file "%s" is not of a valid MIME type. Allowed MIME types: %s.'
                , $name
                , implode(', ', UPLOAD_ALLOWED_MIME_TYPES)
        );
    }

    $nameParts = explode('.', $name);
    $extension = strtolower(end($nameParts));
    // @todo Find a better way to generate a unique filename!
    $uniqueName = substr(md5(time()), 0, 10) . '.' . $extension;
    $uploadPath = rtrim(UPLOAD_DIR, '/') . '/' . $uniqueName;

    // Create the upload directory.
    createDirectory(rtrim(UPLOAD_DIR, '/'));

    // Move the file to the new location.
    if (!move_uploaded_file($tmpName, $uploadPath)) {
        return sprintf('The file "%s" could not be moved to the specified location.'
                , $name
        );
    }

    // Save the file.
    saveFile($connection, $name, $uploadPath);

    return TRUE;
}

/**
 * Save a file.
 *
 * @param PDO $connection Db connection.
 * @param string $name File name.
 * @param string $path File path.
 * @return void
 */
function saveFile($connection, $name, $path) {
    $sql = 'INSERT INTO name (
                name,
                image
            ) VALUES (
                :name,
                :image
            )';

    $statement = $connection->prepare($sql);
    $statement->execute([
        ':name' => $name,
        ':image' => $path,
    ]);
}

/**
 * Create a directory at the specified path.
 *
 * @param string $path Directory path.
 * @return void
 */
function createDirectory($path) {
    if (file_exists($path) && !is_dir($path)) {
        throw new UnexpectedValueException(
        'The upload directory can not be created because a file having the same name already exists!'
        );
    }

    if (!is_dir($path)) {
        mkdir($path, 0777, TRUE);
    }
}

<强>的config.php

<?php

define('UPLOAD_DIR', 'upload/');
define('UPLOAD_MAX_FILE_SIZE', 10485760); // 10MB.
define('UPLOAD_ALLOWED_MIME_TYPES', [
    'image/jpeg',
    'image/png',
    'image/gif',
]);

<强> connection.php

<?php

/*
 * This page contains the code for creating a PDO connection instance.
 */

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');
define('CHARSET', 'utf8');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */

/*
 * Create a PDO instance as db connection to db.
 *
 * @link http://php.net/manual/en/class.pdo.php
 * @link http://php.net/manual/en/pdo.constants.php
 * @link http://php.net/manual/en/pdo.error-handling.php
 * @link http://php.net/manual/en/pdo.connections.php
 */
$connection = new PDO(
        sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
        , USERNAME
        , PASSWORD
        , [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => FALSE,
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
);

<强> upload.css

body {
    margin: 0;
    padding: 20px;
}

.page-container {
    padding: 30px;
    background-color: #f4f4f4;
}

.messages {
    margin-bottom: 20px;
}

.message {
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid transparent;
}

.success {
    color: #3c763d;
    border-color: #d6e9c6;
    background-color: #dff0d8;
}

.danger {
    color: #a94442;
    border-color: #ebccd1;
    background-color: #f2dede;
}

.warning {
    color: #8a6d3b;
    border-color: #faebcc;
    background-color: #fcf8e3;
}

form {
    width: 400px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: inline-block;
    min-width: 40px;
}

button {
    padding: 7px 10px;
    margin: 10px;
    display: block;
    color: #fff;
    font-size: 14px;
    border: none;
    background-color: #8daf15;
}

答案 1 :(得分:-1)

感谢您的帮助和评论Dakis,tadman和yivi

我确实通过此代码解决了这个问题。

public function insertName($data,$file){

    $name = $data['name'];


    $permited  = array('jpg', 'jpeg', 'png', 'gif');
    $file_name = $file['image']['name'];
    $file_size = $file['image']['size'];
    $file_temp = $file['image']['tmp_name'];


    $div = explode('.', $file_name);
    $file_ext = strtolower(end($div));
    $unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
    $uploaded_image = "upload/".$unique_image;


    // $permited  = array('jpg', 'jpeg', 'png', 'gif');
    $file_name_two = $file['imagetwo']['name'];
    $file_size_two = $file['imagetwo']['size'];
    $file_temp_two = $file['imagetwo']['tmp_name'];


    $div_two = explode('.', $file_name_two);
    $file_ext_two = strtolower(end($div_two));
    $unique_image_two = substr(md5(time()), 0, 11).'.'.$file_ext_two;
    $uploaded_image_two = "upload/".$unique_image_two;


    if ($name == "") {
        $msg = '<div class="alert alert-success fade in alert-dismissible" style="margin-top:18px;">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
                    <strong>Warning!</strong> Name Field Must Not Be Empty
                </div>';
        return $msg;
    } else {
        move_uploaded_file($file_temp, $uploaded_image);
        move_uploaded_file($file_temp_two, $uploaded_image_two);

        $stmt = $this->pdo->prepare("INSERT INTO name(`name`, `image`, `imagetwo`) VALUES (:name, :uploaded_image, :uploaded_image_two)");
        $stmt->bindParam(":name", $name);
        $stmt->bindParam(":uploaded_image", $uploaded_image);
        $stmt->bindParam(":uploaded_image_two", $uploaded_image_two);
        $stmt->execute();
        // return $stmt;

        if ($stmt) {
            $msg = '<div class="alert alert-success fade in alert-dismissible" style="margin-top:18px;">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
                    <strong>Success!</strong> Name Inserted Secessfully
                </div>';
            return $msg;
        } else {
            $msg = '
            <div class="alert alert-danger fade in alert-dismissible">
                <a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">×</a>
                <strong>Danger!</strong> Name Not Inserted Secessfully
            </div>';
            return $msg;
        }
    }

} // End Slider Insert Function