MySQL插入表中不会插入

时间:2017-09-23 15:25:40

标签: database insert

我是PHP和MYSQL的新手,正在尝试学习和正在进行的项目。我正在关注个人资料图片的代码教程,我正在尝试上传由特定用户ID上传的多张图片。它可以很好地上传到文件目的地,但我遇到的问题是将它存储到数据库中。

这是我的upload.php

<?php
session_start();

//connection to database
include_once('dbh.inc.php');
$id = $_SESSION['u_id'];

if(isset($_POST['submit'])){
//getting the file
$file = $_FILES['file'];

//file info
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];

$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));

//allowed formats
$allowed = array('jpg','jpeg','png');

//check if the format uploaded is allowed
if(in_array($fileActualExt,$allowed)){
    if($fileError===0){
        if($fileSize < 1000000){
          //setting up for a new file name
          $fileNameNew = $id.".".$fileName.".".$fileActualExt;
          $fileDestination = 'uploads/' . $fileNameNew;
          move_uploaded_file($fileTmpName,$fileDestination);
          //inserting into database
          $sql = "INSERT INTO imageuploads (image,uid_fk) VALUES ('$fileNameNew','$id')";
          mysqli_query($conn,$sql);
          header("Location: ../artsy.php?uploadsuccess");
        }else{
            echo "This file is too large";
        }
    }else{
        echo "There was an error uploading this file";
    }
}else{
    echo "You cannot upload files of this type";
}
}

imageuploads数据库包含&#34; img_id&#34;这是自动递增,&#34;图像&#34;这是一个包含新文件名的varchar,&#34; uid_fk&#34;这是引用用户ID的外键ID。

我没有收到任何错误,但它没有创建新行,但是当我在SQL localhost中运行它时,它很好并创建了一个新行。

1 个答案:

答案 0 :(得分:0)

以下是我如何上传多张图片的示例: https://www.youtube.com/watch?v=GRwMjRNQx6k

这里编码如何上传多个图像(工作示例):

    <?php
session_start();

// dont show errors
error_reporting(0);

// allow big files
ini_set('post_max_size','400M');
ini_set('upload_max_filesize','200M');

// database
$mdatabase = 'test';
$muser = 'root';
$mpass = 'toor';
$mhost = 'localhost';
$mport = 3306;

// connect to mysql with PDO function
function Conn(){
    global $mhost,$mport,$muser,$mpass,$mdatabase;
    $connection = new PDO('mysql:host='.$mhost.';port='.$mport.';dbname='.$mdatabase.';charset=utf8', $muser, $mpass);
    // don't cache query
    $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    // show warning text
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    // throw error exception
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // don't colose connecion on script end
    $connection->setAttribute(PDO::ATTR_PERSISTENT, false);
    // set utf for connection utf8_general_ci or utf8_unicode_ci 
    $connection->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
    return $connection;
}

function saveLink($link, $id = 0){  
    global $db; // allow mysql connection from global variables
    if (!empty($link)) {
        $link = htmlentities($link,ENT_QUOTES,'UTF-8');
        $r = $db->query("INSERT INTO imageuploads (image,uid_fk) VALUES ('$link','$id')");
        // last inserted id if you had auto increment primary key id (int or bigint)
        $id = $db->lastInsertId();
        return $id;
    }else{
        return 0;
    }
}

// db connection
$db = Conn();

//connection to database
$gid = $_SESSION['u_id'] = 777;


//inserting into database
// $sql = "INSERT INTO imageuploads (image,uid_fk) VALUES ('$fileNameNew','$id')";

// echo "<pre>";
// print_r($_FILES);
// 1 MB = 1024 KB = 1 048 576 Bytes = 8 388 608 bitów
$maxsizemb = 1024 * 1024 * 8;
$i = 1;
mkdir("galeria/".$gid, 0755, true);
foreach ($_FILES['files']['type'] as $key => $value) {
    if(($value == "image/png") || ($value == "image/jpg") || ($value == "image/gif") || ($value == "image/jpeg")){
        //echo $value.$_FILES['files']['name'][$key];
        $tmp = $_FILES['files']['tmp_name'][$key];      
        $size = $_FILES['files']['size'][$key]; // bytes
        $name = $_FILES['files']['name'][$key];         
        $temporary = explode(".", $_FILES["files"]["name"][$key]);
        $ext = end($temporary);
        if ($size < $maxsizemb) {
            $fileto = "galeria/".$gid."/".md5(microtime()).".".$ext;
            move_uploaded_file($tmp, $fileto);
            saveLink($fileto, $gid);
            $all[$i] = $fileto; 
        }else{
            echo 'Zbyt duży plik (max 1 MB)';
        }
    }
    $i++;       
}
?>
<form method="post" action="" enctype="multipart/form-data">
    <label>Only JPG</label>
    <input type="file" name="files[]" multiple="true" accept="image/*"><br>
    <!-- or all files -->
    <label>All images</label>
    <input type="file" name="files[]" multiple="true"><br>
    <input type="submit" name="upload" value="UPLOAD">
</form>

和mysql表(数据库名称:test)

-- phpMyAdmin SQL Dump
-- version 4.7.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Czas generowania: 25 Wrz 2017, 07:49
-- Wersja serwera: 10.1.25-MariaDB
-- Wersja PHP: 5.6.31

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Baza danych: `test`
--

-- --------------------------------------------------------

--
-- Struktura tabeli dla tabeli `imageuploads`
--

CREATE TABLE `imageuploads` (
  `id` bigint(21) NOT NULL,
  `image` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `uid_fk` bigint(21) NOT NULL DEFAULT '0',
  `time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indeksy dla zrzutów tabel
--

--
-- Indexes for table `imageuploads`
--
ALTER TABLE `imageuploads`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT dla tabeli `imageuploads`
--
ALTER TABLE `imageuploads`
  MODIFY `id` bigint(21) NOT NULL AUTO_INCREMENT;COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;