将文件上传到数据库PHP / WordPress

时间:2017-10-10 15:05:11

标签: php wordpress

我已创建此PHP代码以将文件上传到我的数据库(phpMyAdmin),但我无法弄清楚如何使其在WordPress上运行。

$con = mysqli_connect("localhost","root","","mydb");
if (mysqli_connect_errno()) {
    echo "Unable to connect to MySQL! ". mysqli_connect_error();
}
if (isset($_POST['submit'])) {
    $target_dir = get_template_directory_uri() .'/Uploaded_Files';
    $target_file = $target_dir . date("dmYhis") . basename($_FILES["file"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if($imageFileType != "jpg" || $imageFileType != "png" || $imageFileType != "jpeg" || $imageFileType != "gif") {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            $files = date("dmYhis") . basename($_FILES["file"]["name"]);
        } else {
            echo "Error Uploading File";
            exit;
        }
    } else {
        echo "File Not Supported";
        exit;
    }
    $filename = $_POST['filename'];
    $location = get_template_directory_uri() .'/Uploaded_Files . $files';
    $getuser = $_SESSION['id'];
    $settime = date("Y-m-d H:i:s");
    $setmsg = $con->real_escape_string($_POST['msg']); 
    // Database Query goes here.
}

2 个答案:

答案 0 :(得分:0)

通常当我们从WordPress中的某个站点导出数据库时,它会显示一个这样的代码,它会提供有关Wordpress插件页面等的表信息。

-- Table structure for table `wp_commentmeta`
--

CREATE TABLE IF NOT EXISTS `wp_commentmeta` (
  `meta_id` bigint(20) unsigned NOT NULL,
  `comment_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_ci
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


AT the head of exported sql sheet it shows... 

-- phpMyAdmin SQL Dump
-- version 4.3.8
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Oct 10, 2017 at 11:57 AM
-- Server version: 5.5.51-38.2
-- PHP Version: 5.6.20

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 utf8 */;

--
-- Database: database name

答案 1 :(得分:0)

首先,当使用WordPress数据库时不使用像mysqli_connect这样的连接,因为WordPress有自己的API与MySQL交互,官方文档:https://codex.wordpress.org/Class_Reference/wpdb

你说"在WordPress数据库中上传文件",我想你的意思是将它添加到媒体库的方式,在这种情况下,本教程应该有帮助https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html