【问题标题】:How to INSERT an array of uploaded filenames into a table and later display them?如何将上传的文件名数组插入表中并稍后显示它们?
【发布时间】:2019-04-01 03:29:54
【问题描述】:

我正在做一个项目,其中每个项目都可以有多个图像,我创建了一个可以接受图像并将它们存储到数组中的表单。问题是每当我尝试将图像插入数据库中的表行时,它都会显示错误:

“数组到字符串的转换”

我该如何解决这个问题?以及如何从同一个数据库表中获取另一个页面上的每个图像。下面是我的代码。

-表单代码

<form method="post" enctype="multipart/form-data" >
    <input required type="text" name="name">
    <input required type="text" name="location">
    <input required type="text" name="status">
    <select required name="category">
        <option>Category</option>
        <option value="construct">Construction</option>           
        <option value="promgt">Project Development</option>           
        <option value="archdesign">Architectural Designs</option>             
    </select>   
    <textarea required class="form-control" name="descrip" rows="5"></textarea>
    <input style="text-align:left" type="file" name="imgs[]" multiple>
    <button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>     

-Addaction.php 代码

<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
    $imgs = $_FILES['imgs'];
    $uploaded = array();
    $failed = array();
    $allowed = array('jpg', 'png');
    foreach($imgs['name'] as $position => $img_name){

        $img_tmp = $imgs['tmp_name'][$position];
        $img_size = $imgs['size'][$position];
        $img_error = $imgs['error'][$position];

        $img_ext = explode('.',$img_name);
        $img_ext = strtolower(end($img_ext));

        if(in_array($img_ext, $allowed)) {

            if($img_error === 0){

                if($img_size <= 500000) {

                    $img_name_new = uniqid('', true) . '.' . $img_ext;
                    $img_destination = 'img/'.$img_name_new;

                    if(move_uploaded_file($img_tmp, $img_destination)){
                        $uploaded[$position] = $img_destination;
                    }else{
                        $failed[$position] = "[{$img_name}] failed to upload";
                    }
                }else{
                    $failed[$position] = "[{$img_name}] is too large";
                }
            }else{
                $failed[$position] = "[{$img_name}] error";
            }
        }else{
            $failed[$position] = "[{$img_name}] file extension";
        }
    }

    if(!empty($uploaded)){
        print_r($uploaded);
    }
    if(!empty($failed)){
        print_r($failed);
    }
}

if(isset($_POST['submit'])){
    $name = $_POST['name'];
    $location = $_POST['location'];
    $status = $_POST['status'];
    $descrip = $_POST['descrip'];   
    $category = $_POST['category'];
    $img_name_new = $_FILES['imgs']['name'];

    if ($db->connect_error){
        die ("Connection Failed: " . $db->connect_error);
    }

    $sql_u = "SELECT * FROM projects WHERE name='$name'";
    $sql_e = "SELECT * FROM projects WHERE category='$category'";
    $res_u = mysqli_query($db, $sql_u);
    $res_e = mysqli_query($db, $sql_e);

    if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
        echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";  
        header("refresh:3 url=add.php");
    }else{
        $sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
    }
    if (mysqli_query($db, $sql_i)){
        echo "Project Added Successfully";
    }else{
        echo mysqli_error($db);
    }

    $db->close();
}
?>

【问题讨论】:

    标签: php arrays database forms mysqli


    【解决方案1】:

    $img_name_new = $_FILES['imgs']['name'] 是一个包含一个或多个图像名称的数组。

    您需要决定如何将数组数据作为字符串存储在数据库中。

    这里有几个合理的选项,但选择最佳选项将取决于您将如何使用这些数据一旦进入数据库。

    1. implode()它——$img_name_new = implode(',', $_FILES['imgs']['name']);
    2. json_encode()它——$img_name_new = json_encode($_FILES['imgs']['name']);

    这是我这一年的好事...

    表单脚本:

    <?php
    if (!$db = new mysqli("localhost", "root", "", "db")) {  // declare and check for a falsey value
        echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
    } else {
        if ($result = $db->query("SELECT name FROM items")) {
            for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
            $result->free();
            ?>
            <script>
                function checkName() {
                    var names = '<?php echo json_encode($rows); ?>';
                    var value = document.forms['project']['name'].value;
                    if (names.indexOf(value) !== -1) {  // might not work on some old browsers
                        alert(value + ' is not a unique name.  Please choose another.');
                        return false;
                    }
                }
            </script>
            <?php
        }
        ?>
        <form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
            Name: <input required type="text" name="name"><br>
            Location: <input required type="text" name="location"><br>
            Status: <input required type="text" name="status"><br>
            Category: <select required name="category">
            <?php
            if ($result = $db->query("SELECT category, category_alias FROM categories")) {
                while ($row = $result->fetch_assoc()) {
                    echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
                }
            }
            ?>
            </select><br>
            <textarea required class="form-control" name="descrip" rows="5"></textarea><br>
            <input style="text-align:left" type="file" name="imgs[]" multiple><br>
            <button type="submit" name="submit" formaction="addaction.php">Add Project</button>
        </form>
        <?php
    }
    

    *请注意,我已经制作了一个单独的category 表进行验证。

    提交处理脚本:(addaction.php)

    <?php
    if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
        $paths = [];
        if (!empty($_FILES['imgs']['name'][0])) {
            $imgs = $_FILES['imgs'];
            $allowed = array('jpg', 'png');
            foreach($imgs['name'] as $position => $img_name){
                $img_tmp = $imgs['tmp_name'][$position];
                $img_size = $imgs['size'][$position];
                $img_error = $imgs['error'][$position];
                $img_ext = strtolower(pathinfo($img_name)['extension']);
                if (!in_array($img_ext, $allowed)) {
                    $errors[] = "File extension is not in whitelist for $img_name ($position)";
                } elseif ($img_error) {
                    $errors[] = "Image error for $img_name ($position): $image_error";
                } elseif ($img_size > 500000) {
                    $errors[] = "Image $image_name ($position) is too large";
                } else {
                    $img_destination = 'img/' . uniqid('', true) . ".$img_ext";
                    if (!move_uploaded_file($img_tmp, $img_destination)) {
                        $errors[] = "Failed to move $img_name ($position) to new directory";
                    } else {
                        $paths[] = $img_destination;
                    }
                 }
             }
        }
    
        if (!empty($errors)) {
            echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
        } elseif (!$db = new mysqli("localhost", "root", "", "db")) {  // declare and check for a falsey value
            echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
        } elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
            echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
        } elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
            echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
        } elseif (!$found) {
            echo "Category Not Found - Project Not Saved";
        } else {
            $stmt->close();
            $cs_paths = (string)implode(',', $paths);
            // Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
            if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
                echo "Error @ prepare"; // $db->error;  // don't show to public
            } elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
                echo "Error @ bind";  // $stmt->error;  // don't show to public
            } elseif (!$stmt->execute()) {
                if ($stmt->errno == 1062) {
                    echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
                } else {
                    echo "Error @ execute" , $stmt->error;  // $stmt->error;  // don't show to public
                }
            } else {
                echo "Project Added Successfully"; 
            }
        }
    }
    

    【讨论】:

    • @Taufiq 我已经更新了我的回答,变得超级慷慨。
    • 不要只是复制粘贴。请阅读每一行代码并尝试理解它的作用以及我这样做的原因。如果有些东西对您没有意义,请参阅 php 手册了解功能详细信息。研究了一下,如果还是不明白,欢迎找我解释。有很多东西需要吸收,但是让自己沉浸在新的/不同的编码风格中,你将体验到巨大的技术增长。我们都在这里互相帮助——我希望你准备好/能够帮助别人。
    • 当你想从你的数据库表中访问逗号分隔的文件名时,你只需要explode()每个,上的值。
    • 这太好了,我终于让它工作了。我被卡住了,我如何分解数组并获取每个图像。我使用 implode 函数插入到数据库中
    • 好吧,我想通了,现在整个项目运行良好。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2013-12-08
    • 2013-02-08
    • 2010-10-01
    • 2013-06-30
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多